babylon.viewer.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080
  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) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(20); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(22); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else {
  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) { // Moving highp to mediump
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else { // Sorry we did everything we can
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @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. //# sourceMappingURL=babylon.types.js.map
  1319. var BABYLON;
  1320. (function (BABYLON) {
  1321. var KeyboardEventTypes = /** @class */ (function () {
  1322. function KeyboardEventTypes() {
  1323. }
  1324. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1325. get: function () {
  1326. return KeyboardEventTypes._KEYDOWN;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1332. get: function () {
  1333. return KeyboardEventTypes._KEYUP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. KeyboardEventTypes._KEYDOWN = 0x01;
  1339. KeyboardEventTypes._KEYUP = 0x02;
  1340. return KeyboardEventTypes;
  1341. }());
  1342. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1343. var KeyboardInfo = /** @class */ (function () {
  1344. function KeyboardInfo(type, event) {
  1345. this.type = type;
  1346. this.event = event;
  1347. }
  1348. return KeyboardInfo;
  1349. }());
  1350. BABYLON.KeyboardInfo = KeyboardInfo;
  1351. /**
  1352. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1353. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1354. */
  1355. var KeyboardInfoPre = /** @class */ (function (_super) {
  1356. __extends(KeyboardInfoPre, _super);
  1357. function KeyboardInfoPre(type, event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.skipOnPointerObservable = false;
  1360. return _this;
  1361. }
  1362. return KeyboardInfoPre;
  1363. }(KeyboardInfo));
  1364. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1365. })(BABYLON || (BABYLON = {}));
  1366. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1367. var BABYLON;
  1368. (function (BABYLON) {
  1369. var PointerEventTypes = /** @class */ (function () {
  1370. function PointerEventTypes() {
  1371. }
  1372. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1373. get: function () {
  1374. return PointerEventTypes._POINTERDOWN;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1380. get: function () {
  1381. return PointerEventTypes._POINTERUP;
  1382. },
  1383. enumerable: true,
  1384. configurable: true
  1385. });
  1386. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1387. get: function () {
  1388. return PointerEventTypes._POINTERMOVE;
  1389. },
  1390. enumerable: true,
  1391. configurable: true
  1392. });
  1393. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1394. get: function () {
  1395. return PointerEventTypes._POINTERWHEEL;
  1396. },
  1397. enumerable: true,
  1398. configurable: true
  1399. });
  1400. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1401. get: function () {
  1402. return PointerEventTypes._POINTERPICK;
  1403. },
  1404. enumerable: true,
  1405. configurable: true
  1406. });
  1407. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1408. get: function () {
  1409. return PointerEventTypes._POINTERTAP;
  1410. },
  1411. enumerable: true,
  1412. configurable: true
  1413. });
  1414. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1415. get: function () {
  1416. return PointerEventTypes._POINTERDOUBLETAP;
  1417. },
  1418. enumerable: true,
  1419. configurable: true
  1420. });
  1421. PointerEventTypes._POINTERDOWN = 0x01;
  1422. PointerEventTypes._POINTERUP = 0x02;
  1423. PointerEventTypes._POINTERMOVE = 0x04;
  1424. PointerEventTypes._POINTERWHEEL = 0x08;
  1425. PointerEventTypes._POINTERPICK = 0x10;
  1426. PointerEventTypes._POINTERTAP = 0x20;
  1427. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1428. return PointerEventTypes;
  1429. }());
  1430. BABYLON.PointerEventTypes = PointerEventTypes;
  1431. var PointerInfoBase = /** @class */ (function () {
  1432. function PointerInfoBase(type, event) {
  1433. this.type = type;
  1434. this.event = event;
  1435. }
  1436. return PointerInfoBase;
  1437. }());
  1438. BABYLON.PointerInfoBase = PointerInfoBase;
  1439. /**
  1440. * This class is used to store pointer related info for the onPrePointerObservable event.
  1441. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1442. */
  1443. var PointerInfoPre = /** @class */ (function (_super) {
  1444. __extends(PointerInfoPre, _super);
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. _this.skipOnPointerObservable = false;
  1448. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1449. return _this;
  1450. }
  1451. return PointerInfoPre;
  1452. }(PointerInfoBase));
  1453. BABYLON.PointerInfoPre = PointerInfoPre;
  1454. /**
  1455. * This type contains all the data related to a pointer event in Babylon.js.
  1456. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1457. */
  1458. var PointerInfo = /** @class */ (function (_super) {
  1459. __extends(PointerInfo, _super);
  1460. function PointerInfo(type, event, pickInfo) {
  1461. var _this = _super.call(this, type, event) || this;
  1462. _this.pickInfo = pickInfo;
  1463. return _this;
  1464. }
  1465. return PointerInfo;
  1466. }(PointerInfoBase));
  1467. BABYLON.PointerInfo = PointerInfo;
  1468. })(BABYLON || (BABYLON = {}));
  1469. //# sourceMappingURL=babylon.pointerEvents.js.map
  1470. var BABYLON;
  1471. (function (BABYLON) {
  1472. BABYLON.ToGammaSpace = 1 / 2.2;
  1473. BABYLON.ToLinearSpace = 2.2;
  1474. BABYLON.Epsilon = 0.001;
  1475. /**
  1476. * Class used to hold a RBG color
  1477. */
  1478. var Color3 = /** @class */ (function () {
  1479. /**
  1480. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1481. * @param r defines the red component (between 0 and 1, default is 0)
  1482. * @param g defines the green component (between 0 and 1, default is 0)
  1483. * @param b defines the blue component (between 0 and 1, default is 0)
  1484. */
  1485. function Color3(
  1486. /**
  1487. * Defines the red component (between 0 and 1, default is 0)
  1488. */
  1489. r,
  1490. /**
  1491. * Defines the green component (between 0 and 1, default is 0)
  1492. */
  1493. g,
  1494. /**
  1495. * Defines the blue component (between 0 and 1, default is 0)
  1496. */
  1497. b) {
  1498. if (r === void 0) { r = 0; }
  1499. if (g === void 0) { g = 0; }
  1500. if (b === void 0) { b = 0; }
  1501. this.r = r;
  1502. this.g = g;
  1503. this.b = b;
  1504. }
  1505. /**
  1506. * Creates a string with the Color3 current values
  1507. * @returns the string representation of the Color3 object
  1508. */
  1509. Color3.prototype.toString = function () {
  1510. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1511. };
  1512. /**
  1513. * Returns the string "Color3"
  1514. * @returns "Color3"
  1515. */
  1516. Color3.prototype.getClassName = function () {
  1517. return "Color3";
  1518. };
  1519. /**
  1520. * Compute the Color3 hash code
  1521. * @returns an unique number that can be used to hash Color3 objects
  1522. */
  1523. Color3.prototype.getHashCode = function () {
  1524. var hash = this.r || 0;
  1525. hash = (hash * 397) ^ (this.g || 0);
  1526. hash = (hash * 397) ^ (this.b || 0);
  1527. return hash;
  1528. };
  1529. // Operators
  1530. /**
  1531. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1532. * @param array defines the array where to store the r,g,b components
  1533. * @param index defines an optional index in the target array to define where to start storing values
  1534. * @returns the current Color3 object
  1535. */
  1536. Color3.prototype.toArray = function (array, index) {
  1537. if (index === undefined) {
  1538. index = 0;
  1539. }
  1540. array[index] = this.r;
  1541. array[index + 1] = this.g;
  1542. array[index + 2] = this.b;
  1543. return this;
  1544. };
  1545. /**
  1546. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1547. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1548. * @returns a new {BABYLON.Color4} object
  1549. */
  1550. Color3.prototype.toColor4 = function (alpha) {
  1551. if (alpha === void 0) { alpha = 1; }
  1552. return new Color4(this.r, this.g, this.b, alpha);
  1553. };
  1554. /**
  1555. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1556. * @returns the new array
  1557. */
  1558. Color3.prototype.asArray = function () {
  1559. var result = new Array();
  1560. this.toArray(result, 0);
  1561. return result;
  1562. };
  1563. /**
  1564. * Returns the luminance value
  1565. * @returns a float value
  1566. */
  1567. Color3.prototype.toLuminance = function () {
  1568. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1569. };
  1570. /**
  1571. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1572. * @param otherColor defines the second operand
  1573. * @returns the new Color3 object
  1574. */
  1575. Color3.prototype.multiply = function (otherColor) {
  1576. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1577. };
  1578. /**
  1579. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1580. * @param otherColor defines the second operand
  1581. * @param result defines the Color3 object where to store the result
  1582. * @returns the current Color3
  1583. */
  1584. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1585. result.r = this.r * otherColor.r;
  1586. result.g = this.g * otherColor.g;
  1587. result.b = this.b * otherColor.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Determines equality between Color3 objects
  1592. * @param otherColor defines the second operand
  1593. * @returns true if the rgb values are equal to the given ones
  1594. */
  1595. Color3.prototype.equals = function (otherColor) {
  1596. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1597. };
  1598. /**
  1599. * Determines equality between the current Color3 object and a set of r,b,g values
  1600. * @param r defines the red component to check
  1601. * @param g defines the green component to check
  1602. * @param b defines the blue component to check
  1603. * @returns true if the rgb values are equal to the given ones
  1604. */
  1605. Color3.prototype.equalsFloats = function (r, g, b) {
  1606. return this.r === r && this.g === g && this.b === b;
  1607. };
  1608. /**
  1609. * Multiplies in place each rgb value by scale
  1610. * @param scale defines the scaling factor
  1611. * @returns the updated Color3
  1612. */
  1613. Color3.prototype.scale = function (scale) {
  1614. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1615. };
  1616. /**
  1617. * Multiplies the rgb values by scale and stores the result into "result"
  1618. * @param scale defines the scaling factor
  1619. * @param result defines the Color3 object where to store the result
  1620. * @returns the unmodified current Color3
  1621. */
  1622. Color3.prototype.scaleToRef = function (scale, result) {
  1623. result.r = this.r * scale;
  1624. result.g = this.g * scale;
  1625. result.b = this.b * scale;
  1626. return this;
  1627. };
  1628. /**
  1629. * Scale the current Color3 values by a factor and add the result to a given Color3
  1630. * @param scale defines the scale factor
  1631. * @param result defines color to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1635. result.r += this.r * scale;
  1636. result.g += this.g * scale;
  1637. result.b += this.b * scale;
  1638. return this;
  1639. };
  1640. /**
  1641. * Clamps the rgb values by the min and max values and stores the result into "result"
  1642. * @param min defines minimum clamping value (default is 0)
  1643. * @param max defines maximum clamping value (default is 1)
  1644. * @param result defines color to store the result into
  1645. * @returns the original Color3
  1646. */
  1647. Color3.prototype.clampToRef = function (min, max, result) {
  1648. if (min === void 0) { min = 0; }
  1649. if (max === void 0) { max = 1; }
  1650. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1651. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1652. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1653. return this;
  1654. };
  1655. /**
  1656. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1657. * @param otherColor defines the second operand
  1658. * @returns the new Color3
  1659. */
  1660. Color3.prototype.add = function (otherColor) {
  1661. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1662. };
  1663. /**
  1664. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1665. * @param otherColor defines the second operand
  1666. * @param result defines Color3 object to store the result into
  1667. * @returns the unmodified current Color3
  1668. */
  1669. Color3.prototype.addToRef = function (otherColor, result) {
  1670. result.r = this.r + otherColor.r;
  1671. result.g = this.g + otherColor.g;
  1672. result.b = this.b + otherColor.b;
  1673. return this;
  1674. };
  1675. /**
  1676. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1677. * @param otherColor defines the second operand
  1678. * @returns the new Color3
  1679. */
  1680. Color3.prototype.subtract = function (otherColor) {
  1681. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1682. };
  1683. /**
  1684. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1685. * @param otherColor defines the second operand
  1686. * @param result defines Color3 object to store the result into
  1687. * @returns the unmodified current Color3
  1688. */
  1689. Color3.prototype.subtractToRef = function (otherColor, result) {
  1690. result.r = this.r - otherColor.r;
  1691. result.g = this.g - otherColor.g;
  1692. result.b = this.b - otherColor.b;
  1693. return this;
  1694. };
  1695. /**
  1696. * Copy the current object
  1697. * @returns a new Color3 copied the current one
  1698. */
  1699. Color3.prototype.clone = function () {
  1700. return new Color3(this.r, this.g, this.b);
  1701. };
  1702. /**
  1703. * Copies the rgb values from the source in the current Color3
  1704. * @param source defines the source Color3 object
  1705. * @returns the updated Color3 object
  1706. */
  1707. Color3.prototype.copyFrom = function (source) {
  1708. this.r = source.r;
  1709. this.g = source.g;
  1710. this.b = source.b;
  1711. return this;
  1712. };
  1713. /**
  1714. * Updates the Color3 rgb values from the given floats
  1715. * @param r defines the red component to read from
  1716. * @param g defines the green component to read from
  1717. * @param b defines the blue component to read from
  1718. * @returns the current Color3 object
  1719. */
  1720. Color3.prototype.copyFromFloats = function (r, g, b) {
  1721. this.r = r;
  1722. this.g = g;
  1723. this.b = b;
  1724. return this;
  1725. };
  1726. /**
  1727. * Updates the Color3 rgb values from the given floats
  1728. * @param r defines the red component to read from
  1729. * @param g defines the green component to read from
  1730. * @param b defines the blue component to read from
  1731. * @returns the current Color3 object
  1732. */
  1733. Color3.prototype.set = function (r, g, b) {
  1734. return this.copyFromFloats(r, g, b);
  1735. };
  1736. /**
  1737. * Compute the Color3 hexadecimal code as a string
  1738. * @returns a string containing the hexadecimal representation of the Color3 object
  1739. */
  1740. Color3.prototype.toHexString = function () {
  1741. var intR = (this.r * 255) | 0;
  1742. var intG = (this.g * 255) | 0;
  1743. var intB = (this.b * 255) | 0;
  1744. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1745. };
  1746. /**
  1747. * Computes a new Color3 converted from the current one to linear space
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.prototype.toLinearSpace = function () {
  1751. var convertedColor = new Color3();
  1752. this.toLinearSpaceToRef(convertedColor);
  1753. return convertedColor;
  1754. };
  1755. /**
  1756. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1757. * @param convertedColor defines the Color3 object where to store the linear space version
  1758. * @returns the unmodified Color3
  1759. */
  1760. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1761. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1762. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1763. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1764. return this;
  1765. };
  1766. /**
  1767. * Computes a new Color3 converted from the current one to gamma space
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.prototype.toGammaSpace = function () {
  1771. var convertedColor = new Color3();
  1772. this.toGammaSpaceToRef(convertedColor);
  1773. return convertedColor;
  1774. };
  1775. /**
  1776. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1777. * @param convertedColor defines the Color3 object where to store the gamma space version
  1778. * @returns the unmodified Color3
  1779. */
  1780. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1781. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1782. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1783. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1784. return this;
  1785. };
  1786. // Statics
  1787. /**
  1788. * Creates a new Color3 from the string containing valid hexadecimal values
  1789. * @param hex defines a string containing valid hexadecimal values
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromHexString = function (hex) {
  1793. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1794. return new Color3(0, 0, 0);
  1795. }
  1796. var r = parseInt(hex.substring(1, 3), 16);
  1797. var g = parseInt(hex.substring(3, 5), 16);
  1798. var b = parseInt(hex.substring(5, 7), 16);
  1799. return Color3.FromInts(r, g, b);
  1800. };
  1801. /**
  1802. * Creates a new Vector3 from the starting index of the given array
  1803. * @param array defines the source array
  1804. * @param offset defines an offset in the source array
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.FromArray = function (array, offset) {
  1808. if (offset === void 0) { offset = 0; }
  1809. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1810. };
  1811. /**
  1812. * Creates a new Color3 from integer values (< 256)
  1813. * @param r defines the red component to read from (value between 0 and 255)
  1814. * @param g defines the green component to read from (value between 0 and 255)
  1815. * @param b defines the blue component to read from (value between 0 and 255)
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromInts = function (r, g, b) {
  1819. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1820. };
  1821. /**
  1822. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1823. * @param start defines the start Color3 value
  1824. * @param end defines the end Color3 value
  1825. * @param amount defines the gradient value between start and end
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Lerp = function (start, end, amount) {
  1829. var r = start.r + ((end.r - start.r) * amount);
  1830. var g = start.g + ((end.g - start.g) * amount);
  1831. var b = start.b + ((end.b - start.b) * amount);
  1832. return new Color3(r, g, b);
  1833. };
  1834. /**
  1835. * Returns a Color3 value containing a red color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Red = function () { return new Color3(1, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a green color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Green = function () { return new Color3(0, 1, 0); };
  1844. /**
  1845. * Returns a Color3 value containing a blue color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1849. /**
  1850. * Returns a Color3 value containing a black color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Black = function () { return new Color3(0, 0, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a white color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.White = function () { return new Color3(1, 1, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a purple color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a magenta color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a yellow color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1874. /**
  1875. * Returns a Color3 value containing a gray color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1879. /**
  1880. * Returns a Color3 value containing a teal color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1884. /**
  1885. * Returns a Color3 value containing a random color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1889. return Color3;
  1890. }());
  1891. BABYLON.Color3 = Color3;
  1892. /**
  1893. * Class used to hold a RBGA color
  1894. */
  1895. var Color4 = /** @class */ (function () {
  1896. /**
  1897. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1898. * @param r defines the red component (between 0 and 1, default is 0)
  1899. * @param g defines the green component (between 0 and 1, default is 0)
  1900. * @param b defines the blue component (between 0 and 1, default is 0)
  1901. * @param a defines the alpha component (between 0 and 1, default is 1)
  1902. */
  1903. function Color4(
  1904. /**
  1905. * Defines the red component (between 0 and 1, default is 0)
  1906. */
  1907. r,
  1908. /**
  1909. * Defines the green component (between 0 and 1, default is 0)
  1910. */
  1911. g,
  1912. /**
  1913. * Defines the blue component (between 0 and 1, default is 0)
  1914. */
  1915. b,
  1916. /**
  1917. * Defines the alpha component (between 0 and 1, default is 1)
  1918. */
  1919. a) {
  1920. if (r === void 0) { r = 0; }
  1921. if (g === void 0) { g = 0; }
  1922. if (b === void 0) { b = 0; }
  1923. if (a === void 0) { a = 1; }
  1924. this.r = r;
  1925. this.g = g;
  1926. this.b = b;
  1927. this.a = a;
  1928. }
  1929. // Operators
  1930. /**
  1931. * Adds in place the given Color4 values to the current Color4 object
  1932. * @param right defines the second operand
  1933. * @returns the current updated Color4 object
  1934. */
  1935. Color4.prototype.addInPlace = function (right) {
  1936. this.r += right.r;
  1937. this.g += right.g;
  1938. this.b += right.b;
  1939. this.a += right.a;
  1940. return this;
  1941. };
  1942. /**
  1943. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1944. * @returns the new array
  1945. */
  1946. Color4.prototype.asArray = function () {
  1947. var result = new Array();
  1948. this.toArray(result, 0);
  1949. return result;
  1950. };
  1951. /**
  1952. * Stores from the starting index in the given array the Color4 successive values
  1953. * @param array defines the array where to store the r,g,b components
  1954. * @param index defines an optional index in the target array to define where to start storing values
  1955. * @returns the current Color4 object
  1956. */
  1957. Color4.prototype.toArray = function (array, index) {
  1958. if (index === undefined) {
  1959. index = 0;
  1960. }
  1961. array[index] = this.r;
  1962. array[index + 1] = this.g;
  1963. array[index + 2] = this.b;
  1964. array[index + 3] = this.a;
  1965. return this;
  1966. };
  1967. /**
  1968. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1969. * @param right defines the second operand
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.add = function (right) {
  1973. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1974. };
  1975. /**
  1976. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1977. * @param right defines the second operand
  1978. * @returns a new Color4 object
  1979. */
  1980. Color4.prototype.subtract = function (right) {
  1981. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1982. };
  1983. /**
  1984. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1985. * @param right defines the second operand
  1986. * @param result defines the Color4 object where to store the result
  1987. * @returns the current Color4 object
  1988. */
  1989. Color4.prototype.subtractToRef = function (right, result) {
  1990. result.r = this.r - right.r;
  1991. result.g = this.g - right.g;
  1992. result.b = this.b - right.b;
  1993. result.a = this.a - right.a;
  1994. return this;
  1995. };
  1996. /**
  1997. * Creates a new Color4 with the current Color4 values multiplied by scale
  1998. * @param scale defines the scaling factor to apply
  1999. * @returns a new Color4 object
  2000. */
  2001. Color4.prototype.scale = function (scale) {
  2002. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2003. };
  2004. /**
  2005. * Multiplies the current Color4 values by scale and stores the result in "result"
  2006. * @param scale defines the scaling factor to apply
  2007. * @param result defines the Color4 object where to store the result
  2008. * @returns the current unmodified Color4
  2009. */
  2010. Color4.prototype.scaleToRef = function (scale, result) {
  2011. result.r = this.r * scale;
  2012. result.g = this.g * scale;
  2013. result.b = this.b * scale;
  2014. result.a = this.a * scale;
  2015. return this;
  2016. };
  2017. /**
  2018. * Scale the current Color4 values by a factor and add the result to a given Color4
  2019. * @param scale defines the scale factor
  2020. * @param result defines the Color4 object where to store the result
  2021. * @returns the unmodified current Color4
  2022. */
  2023. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2024. result.r += this.r * scale;
  2025. result.g += this.g * scale;
  2026. result.b += this.b * scale;
  2027. result.a += this.a * scale;
  2028. return this;
  2029. };
  2030. /**
  2031. * Clamps the rgb values by the min and max values and stores the result into "result"
  2032. * @param min defines minimum clamping value (default is 0)
  2033. * @param max defines maximum clamping value (default is 1)
  2034. * @param result defines color to store the result into.
  2035. * @returns the cuurent Color4
  2036. */
  2037. Color4.prototype.clampToRef = function (min, max, result) {
  2038. if (min === void 0) { min = 0; }
  2039. if (max === void 0) { max = 1; }
  2040. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2041. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2042. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2043. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2044. return this;
  2045. };
  2046. /**
  2047. * Multipy an Color4 value by another and return a new Color4 object
  2048. * @param color defines the Color4 value to multiply by
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.prototype.multiply = function (color) {
  2052. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2053. };
  2054. /**
  2055. * Multipy a Color4 value by another and push the result in a reference value
  2056. * @param color defines the Color4 value to multiply by
  2057. * @param result defines the Color4 to fill the result in
  2058. * @returns the result Color4
  2059. */
  2060. Color4.prototype.multiplyToRef = function (color, result) {
  2061. result.r = this.r * color.r;
  2062. result.g = this.g * color.g;
  2063. result.b = this.b * color.b;
  2064. result.a = this.a * color.a;
  2065. return result;
  2066. };
  2067. /**
  2068. * Creates a string with the Color4 current values
  2069. * @returns the string representation of the Color4 object
  2070. */
  2071. Color4.prototype.toString = function () {
  2072. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2073. };
  2074. /**
  2075. * Returns the string "Color4"
  2076. * @returns "Color4"
  2077. */
  2078. Color4.prototype.getClassName = function () {
  2079. return "Color4";
  2080. };
  2081. /**
  2082. * Compute the Color4 hash code
  2083. * @returns an unique number that can be used to hash Color4 objects
  2084. */
  2085. Color4.prototype.getHashCode = function () {
  2086. var hash = this.r || 0;
  2087. hash = (hash * 397) ^ (this.g || 0);
  2088. hash = (hash * 397) ^ (this.b || 0);
  2089. hash = (hash * 397) ^ (this.a || 0);
  2090. return hash;
  2091. };
  2092. /**
  2093. * Creates a new Color4 copied from the current one
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.clone = function () {
  2097. return new Color4(this.r, this.g, this.b, this.a);
  2098. };
  2099. /**
  2100. * Copies the given Color4 values into the current one
  2101. * @param source defines the source Color4 object
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFrom = function (source) {
  2105. this.r = source.r;
  2106. this.g = source.g;
  2107. this.b = source.b;
  2108. this.a = source.a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2120. this.r = r;
  2121. this.g = g;
  2122. this.b = b;
  2123. this.a = a;
  2124. return this;
  2125. };
  2126. /**
  2127. * Copies the given float values into the current one
  2128. * @param r defines the red component to read from
  2129. * @param g defines the green component to read from
  2130. * @param b defines the blue component to read from
  2131. * @param a defines the alpha component to read from
  2132. * @returns the current updated Color4 object
  2133. */
  2134. Color4.prototype.set = function (r, g, b, a) {
  2135. return this.copyFromFloats(r, g, b, a);
  2136. };
  2137. /**
  2138. * Compute the Color4 hexadecimal code as a string
  2139. * @returns a string containing the hexadecimal representation of the Color4 object
  2140. */
  2141. Color4.prototype.toHexString = function () {
  2142. var intR = (this.r * 255) | 0;
  2143. var intG = (this.g * 255) | 0;
  2144. var intB = (this.b * 255) | 0;
  2145. var intA = (this.a * 255) | 0;
  2146. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2147. };
  2148. /**
  2149. * Computes a new Color4 converted from the current one to linear space
  2150. * @returns a new Color4 object
  2151. */
  2152. Color4.prototype.toLinearSpace = function () {
  2153. var convertedColor = new Color4();
  2154. this.toLinearSpaceToRef(convertedColor);
  2155. return convertedColor;
  2156. };
  2157. /**
  2158. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2159. * @param convertedColor defines the Color4 object where to store the linear space version
  2160. * @returns the unmodified Color4
  2161. */
  2162. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2163. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2164. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2165. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2166. convertedColor.a = this.a;
  2167. return this;
  2168. };
  2169. /**
  2170. * Computes a new Color4 converted from the current one to gamma space
  2171. * @returns a new Color4 object
  2172. */
  2173. Color4.prototype.toGammaSpace = function () {
  2174. var convertedColor = new Color4();
  2175. this.toGammaSpaceToRef(convertedColor);
  2176. return convertedColor;
  2177. };
  2178. /**
  2179. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2180. * @param convertedColor defines the Color4 object where to store the gamma space version
  2181. * @returns the unmodified Color4
  2182. */
  2183. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2184. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2185. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2186. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2187. convertedColor.a = this.a;
  2188. return this;
  2189. };
  2190. // Statics
  2191. /**
  2192. * Creates a new Color4 from the string containing valid hexadecimal values
  2193. * @param hex defines a string containing valid hexadecimal values
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.FromHexString = function (hex) {
  2197. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2198. return new Color4(0.0, 0.0, 0.0, 0.0);
  2199. }
  2200. var r = parseInt(hex.substring(1, 3), 16);
  2201. var g = parseInt(hex.substring(3, 5), 16);
  2202. var b = parseInt(hex.substring(5, 7), 16);
  2203. var a = parseInt(hex.substring(7, 9), 16);
  2204. return Color4.FromInts(r, g, b, a);
  2205. };
  2206. /**
  2207. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2208. * @param left defines the start value
  2209. * @param right defines the end value
  2210. * @param amount defines the gradient factor
  2211. * @returns a new Color4 object
  2212. */
  2213. Color4.Lerp = function (left, right, amount) {
  2214. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2215. Color4.LerpToRef(left, right, amount, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @param result defines the Color4 object where to store data
  2224. */
  2225. Color4.LerpToRef = function (left, right, amount, result) {
  2226. result.r = left.r + (right.r - left.r) * amount;
  2227. result.g = left.g + (right.g - left.g) * amount;
  2228. result.b = left.b + (right.b - left.b) * amount;
  2229. result.a = left.a + (right.a - left.a) * amount;
  2230. };
  2231. /**
  2232. * Creates a new Color4 from the starting index element of the given array
  2233. * @param array defines the source array to read from
  2234. * @param offset defines the offset in the source array
  2235. * @returns a new Color4 object
  2236. */
  2237. Color4.FromArray = function (array, offset) {
  2238. if (offset === void 0) { offset = 0; }
  2239. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2240. };
  2241. /**
  2242. * Creates a new Color3 from integer values (< 256)
  2243. * @param r defines the red component to read from (value between 0 and 255)
  2244. * @param g defines the green component to read from (value between 0 and 255)
  2245. * @param b defines the blue component to read from (value between 0 and 255)
  2246. * @param a defines the alpha component to read from (value between 0 and 255)
  2247. * @returns a new Color3 object
  2248. */
  2249. Color4.FromInts = function (r, g, b, a) {
  2250. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2251. };
  2252. /**
  2253. * Check the content of a given array and convert it to an array containing RGBA data
  2254. * If the original array was already containing count * 4 values then it is returned directly
  2255. * @param colors defines the array to check
  2256. * @param count defines the number of RGBA data to expect
  2257. * @returns an array containing count * 4 values (RGBA)
  2258. */
  2259. Color4.CheckColors4 = function (colors, count) {
  2260. // Check if color3 was used
  2261. if (colors.length === count * 3) {
  2262. var colors4 = [];
  2263. for (var index = 0; index < colors.length; index += 3) {
  2264. var newIndex = (index / 3) * 4;
  2265. colors4[newIndex] = colors[index];
  2266. colors4[newIndex + 1] = colors[index + 1];
  2267. colors4[newIndex + 2] = colors[index + 2];
  2268. colors4[newIndex + 3] = 1.0;
  2269. }
  2270. return colors4;
  2271. }
  2272. return colors;
  2273. };
  2274. return Color4;
  2275. }());
  2276. BABYLON.Color4 = Color4;
  2277. var Vector2 = /** @class */ (function () {
  2278. /**
  2279. * Creates a new Vector2 from the given x and y coordinates.
  2280. */
  2281. function Vector2(x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. }
  2285. /**
  2286. * Returns a string with the Vector2 coordinates.
  2287. */
  2288. Vector2.prototype.toString = function () {
  2289. return "{X: " + this.x + " Y:" + this.y + "}";
  2290. };
  2291. /**
  2292. * Returns the string "Vector2"
  2293. */
  2294. Vector2.prototype.getClassName = function () {
  2295. return "Vector2";
  2296. };
  2297. /**
  2298. * Returns the Vector2 hash code as a number.
  2299. */
  2300. Vector2.prototype.getHashCode = function () {
  2301. var hash = this.x || 0;
  2302. hash = (hash * 397) ^ (this.y || 0);
  2303. return hash;
  2304. };
  2305. // Operators
  2306. /**
  2307. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2308. * Returns the Vector2.
  2309. */
  2310. Vector2.prototype.toArray = function (array, index) {
  2311. if (index === void 0) { index = 0; }
  2312. array[index] = this.x;
  2313. array[index + 1] = this.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Returns a new array with 2 elements : the Vector2 coordinates.
  2318. */
  2319. Vector2.prototype.asArray = function () {
  2320. var result = new Array();
  2321. this.toArray(result, 0);
  2322. return result;
  2323. };
  2324. /**
  2325. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2326. * Returns the updated Vector2.
  2327. */
  2328. Vector2.prototype.copyFrom = function (source) {
  2329. this.x = source.x;
  2330. this.y = source.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Sets the Vector2 coordinates with the given floats.
  2335. * Returns the updated Vector2.
  2336. */
  2337. Vector2.prototype.copyFromFloats = function (x, y) {
  2338. this.x = x;
  2339. this.y = y;
  2340. return this;
  2341. };
  2342. /**
  2343. * Sets the Vector2 coordinates with the given floats.
  2344. * Returns the updated Vector2.
  2345. */
  2346. Vector2.prototype.set = function (x, y) {
  2347. return this.copyFromFloats(x, y);
  2348. };
  2349. /**
  2350. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2351. */
  2352. Vector2.prototype.add = function (otherVector) {
  2353. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2354. };
  2355. /**
  2356. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2357. * Returns the Vector2.
  2358. */
  2359. Vector2.prototype.addToRef = function (otherVector, result) {
  2360. result.x = this.x + otherVector.x;
  2361. result.y = this.y + otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2366. * Returns the updated Vector2.
  2367. */
  2368. Vector2.prototype.addInPlace = function (otherVector) {
  2369. this.x += otherVector.x;
  2370. this.y += otherVector.y;
  2371. return this;
  2372. };
  2373. /**
  2374. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2375. */
  2376. Vector2.prototype.addVector3 = function (otherVector) {
  2377. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2378. };
  2379. /**
  2380. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2381. */
  2382. Vector2.prototype.subtract = function (otherVector) {
  2383. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2384. };
  2385. /**
  2386. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2387. * Returns the Vector2.
  2388. */
  2389. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2390. result.x = this.x - otherVector.x;
  2391. result.y = this.y - otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2396. * Returns the updated Vector2.
  2397. */
  2398. Vector2.prototype.subtractInPlace = function (otherVector) {
  2399. this.x -= otherVector.x;
  2400. this.y -= otherVector.y;
  2401. return this;
  2402. };
  2403. /**
  2404. * Multiplies in place the current Vector2 coordinates by the given ones.
  2405. * Returns the updated Vector2.
  2406. */
  2407. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2408. this.x *= otherVector.x;
  2409. this.y *= otherVector.y;
  2410. return this;
  2411. };
  2412. /**
  2413. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2414. */
  2415. Vector2.prototype.multiply = function (otherVector) {
  2416. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2417. };
  2418. /**
  2419. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2420. * Returns the Vector2.
  2421. */
  2422. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2423. result.x = this.x * otherVector.x;
  2424. result.y = this.y * otherVector.y;
  2425. return this;
  2426. };
  2427. /**
  2428. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2429. */
  2430. Vector2.prototype.multiplyByFloats = function (x, y) {
  2431. return new Vector2(this.x * x, this.y * y);
  2432. };
  2433. /**
  2434. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2435. */
  2436. Vector2.prototype.divide = function (otherVector) {
  2437. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2438. };
  2439. /**
  2440. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2441. * Returns the Vector2.
  2442. */
  2443. Vector2.prototype.divideToRef = function (otherVector, result) {
  2444. result.x = this.x / otherVector.x;
  2445. result.y = this.y / otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Divides the current Vector3 coordinates by the given ones.
  2450. * Returns the updated Vector3.
  2451. */
  2452. Vector2.prototype.divideInPlace = function (otherVector) {
  2453. return this.divideToRef(otherVector, this);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 with current Vector2 negated coordinates.
  2457. */
  2458. Vector2.prototype.negate = function () {
  2459. return new Vector2(-this.x, -this.y);
  2460. };
  2461. /**
  2462. * Multiply the Vector2 coordinates by scale.
  2463. * Returns the updated Vector2.
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2472. */
  2473. Vector2.prototype.scale = function (scale) {
  2474. var result = new Vector2(0, 0);
  2475. this.scaleToRef(scale, result);
  2476. return result;
  2477. };
  2478. /**
  2479. * Scale the current Vector2 values by a factor to a given Vector2
  2480. * @param scale defines the scale factor
  2481. * @param result defines the Vector2 object where to store the result
  2482. * @returns the unmodified current Vector2
  2483. */
  2484. Vector2.prototype.scaleToRef = function (scale, result) {
  2485. result.x = this.x * scale;
  2486. result.y = this.y * scale;
  2487. return this;
  2488. };
  2489. /**
  2490. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2491. * @param scale defines the scale factor
  2492. * @param result defines the Vector2 object where to store the result
  2493. * @returns the unmodified current Vector2
  2494. */
  2495. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2496. result.x += this.x * scale;
  2497. result.y += this.y * scale;
  2498. return this;
  2499. };
  2500. /**
  2501. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2502. */
  2503. Vector2.prototype.equals = function (otherVector) {
  2504. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2505. };
  2506. /**
  2507. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2508. */
  2509. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2510. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2511. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2512. };
  2513. // Properties
  2514. /**
  2515. * Returns the vector length (float).
  2516. */
  2517. Vector2.prototype.length = function () {
  2518. return Math.sqrt(this.x * this.x + this.y * this.y);
  2519. };
  2520. /**
  2521. * Returns the vector squared length (float);
  2522. */
  2523. Vector2.prototype.lengthSquared = function () {
  2524. return (this.x * this.x + this.y * this.y);
  2525. };
  2526. // Methods
  2527. /**
  2528. * Normalize the vector.
  2529. * Returns the updated Vector2.
  2530. */
  2531. Vector2.prototype.normalize = function () {
  2532. var len = this.length();
  2533. if (len === 0)
  2534. return this;
  2535. var num = 1.0 / len;
  2536. this.x *= num;
  2537. this.y *= num;
  2538. return this;
  2539. };
  2540. /**
  2541. * Returns a new Vector2 copied from the Vector2.
  2542. */
  2543. Vector2.prototype.clone = function () {
  2544. return new Vector2(this.x, this.y);
  2545. };
  2546. // Statics
  2547. /**
  2548. * Returns a new Vector2(0, 0)
  2549. */
  2550. Vector2.Zero = function () {
  2551. return new Vector2(0, 0);
  2552. };
  2553. /**
  2554. * Returns a new Vector2(1, 1)
  2555. */
  2556. Vector2.One = function () {
  2557. return new Vector2(1, 1);
  2558. };
  2559. /**
  2560. * Returns a new Vector2 set from the given index element of the given array.
  2561. */
  2562. Vector2.FromArray = function (array, offset) {
  2563. if (offset === void 0) { offset = 0; }
  2564. return new Vector2(array[offset], array[offset + 1]);
  2565. };
  2566. /**
  2567. * Sets "result" from the given index element of the given array.
  2568. */
  2569. Vector2.FromArrayToRef = function (array, offset, result) {
  2570. result.x = array[offset];
  2571. result.y = array[offset + 1];
  2572. };
  2573. /**
  2574. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2575. */
  2576. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2577. var squared = amount * amount;
  2578. var cubed = amount * squared;
  2579. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2580. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2581. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2582. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2583. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2584. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2585. return new Vector2(x, y);
  2586. };
  2587. /**
  2588. * 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".
  2589. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2590. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2603. */
  2604. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2605. var squared = amount * amount;
  2606. var cubed = amount * squared;
  2607. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2608. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2609. var part3 = (cubed - (2.0 * squared)) + amount;
  2610. var part4 = cubed - squared;
  2611. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2612. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2613. return new Vector2(x, y);
  2614. };
  2615. /**
  2616. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2617. */
  2618. Vector2.Lerp = function (start, end, amount) {
  2619. var x = start.x + ((end.x - start.x) * amount);
  2620. var y = start.y + ((end.y - start.y) * amount);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns the dot product (float) of the vector "left" and the vector "right".
  2625. */
  2626. Vector2.Dot = function (left, right) {
  2627. return left.x * right.x + left.y * right.y;
  2628. };
  2629. /**
  2630. * Returns a new Vector2 equal to the normalized given vector.
  2631. */
  2632. Vector2.Normalize = function (vector) {
  2633. var newVector = vector.clone();
  2634. newVector.normalize();
  2635. return newVector;
  2636. };
  2637. /**
  2638. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2639. */
  2640. Vector2.Minimize = function (left, right) {
  2641. var x = (left.x < right.x) ? left.x : right.x;
  2642. var y = (left.y < right.y) ? left.y : right.y;
  2643. return new Vector2(x, y);
  2644. };
  2645. /**
  2646. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2647. */
  2648. Vector2.Maximize = function (left, right) {
  2649. var x = (left.x > right.x) ? left.x : right.x;
  2650. var y = (left.y > right.y) ? left.y : right.y;
  2651. return new Vector2(x, y);
  2652. };
  2653. /**
  2654. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2655. */
  2656. Vector2.Transform = function (vector, transformation) {
  2657. var r = Vector2.Zero();
  2658. Vector2.TransformToRef(vector, transformation, r);
  2659. return r;
  2660. };
  2661. /**
  2662. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2672. */
  2673. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2674. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2675. var sign = a < 0 ? -1 : 1;
  2676. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2677. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2678. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2679. };
  2680. /**
  2681. * Returns the distance (float) between the vectors "value1" and "value2".
  2682. */
  2683. Vector2.Distance = function (value1, value2) {
  2684. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2685. };
  2686. /**
  2687. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2688. */
  2689. Vector2.DistanceSquared = function (value1, value2) {
  2690. var x = value1.x - value2.x;
  2691. var y = value1.y - value2.y;
  2692. return (x * x) + (y * y);
  2693. };
  2694. /**
  2695. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2696. */
  2697. Vector2.Center = function (value1, value2) {
  2698. var center = value1.add(value2);
  2699. center.scaleInPlace(0.5);
  2700. return center;
  2701. };
  2702. /**
  2703. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2704. */
  2705. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2706. var l2 = Vector2.DistanceSquared(segA, segB);
  2707. if (l2 === 0.0) {
  2708. return Vector2.Distance(p, segA);
  2709. }
  2710. var v = segB.subtract(segA);
  2711. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2712. var proj = segA.add(v.multiplyByFloats(t, t));
  2713. return Vector2.Distance(p, proj);
  2714. };
  2715. return Vector2;
  2716. }());
  2717. BABYLON.Vector2 = Vector2;
  2718. /**
  2719. * Classed used to store (x,y,z) vector representation
  2720. * A Vector3 is the main object used in 3D geometry
  2721. * It can represent etiher the coordinates of a point the space, either a direction
  2722. * Reminder: Babylon.js uses a left handed forward facing system
  2723. */
  2724. var Vector3 = /** @class */ (function () {
  2725. /**
  2726. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2727. * @param x defines the first coordinates (on X axis)
  2728. * @param y defines the second coordinates (on Y axis)
  2729. * @param z defines the third coordinates (on Z axis)
  2730. */
  2731. function Vector3(
  2732. /**
  2733. * Defines the first coordinates (on X axis)
  2734. */
  2735. x,
  2736. /**
  2737. * Defines the second coordinates (on Y axis)
  2738. */
  2739. y,
  2740. /**
  2741. * Defines the third coordinates (on Z axis)
  2742. */
  2743. z) {
  2744. this.x = x;
  2745. this.y = y;
  2746. this.z = z;
  2747. }
  2748. /**
  2749. * Creates a string representation of the Vector3
  2750. * @returns a string with the Vector3 coordinates.
  2751. */
  2752. Vector3.prototype.toString = function () {
  2753. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2754. };
  2755. /**
  2756. * Gets the class name
  2757. * @returns the string "Vector3"
  2758. */
  2759. Vector3.prototype.getClassName = function () {
  2760. return "Vector3";
  2761. };
  2762. /**
  2763. * Creates the Vector3 hash code
  2764. * @returns a number which tends to be unique between Vector3 instances
  2765. */
  2766. Vector3.prototype.getHashCode = function () {
  2767. var hash = this.x || 0;
  2768. hash = (hash * 397) ^ (this.y || 0);
  2769. hash = (hash * 397) ^ (this.z || 0);
  2770. return hash;
  2771. };
  2772. // Operators
  2773. /**
  2774. * Creates an array containing three elements : the coordinates of the Vector3
  2775. * @returns a new array of numbers
  2776. */
  2777. Vector3.prototype.asArray = function () {
  2778. var result = [];
  2779. this.toArray(result, 0);
  2780. return result;
  2781. };
  2782. /**
  2783. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2784. * @param array defines the destination array
  2785. * @param index defines the offset in the destination array
  2786. * @returns the current Vector3
  2787. */
  2788. Vector3.prototype.toArray = function (array, index) {
  2789. if (index === void 0) { index = 0; }
  2790. array[index] = this.x;
  2791. array[index + 1] = this.y;
  2792. array[index + 2] = this.z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2797. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2798. */
  2799. Vector3.prototype.toQuaternion = function () {
  2800. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2801. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2802. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2803. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2804. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2805. var cosy = Math.cos(this.y * 0.5);
  2806. var siny = Math.sin(this.y * 0.5);
  2807. result.x = coszMinusx * siny;
  2808. result.y = -sinzMinusx * siny;
  2809. result.z = sinxPlusz * cosy;
  2810. result.w = cosxPlusz * cosy;
  2811. return result;
  2812. };
  2813. /**
  2814. * Adds the given vector to the current Vector3
  2815. * @param otherVector defines the second operand
  2816. * @returns the current updated Vector3
  2817. */
  2818. Vector3.prototype.addInPlace = function (otherVector) {
  2819. this.x += otherVector.x;
  2820. this.y += otherVector.y;
  2821. this.z += otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2826. * @param otherVector defines the second operand
  2827. * @returns the resulting Vector3
  2828. */
  2829. Vector3.prototype.add = function (otherVector) {
  2830. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2831. };
  2832. /**
  2833. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2834. * @param otherVector defines the second operand
  2835. * @param result defines the Vector3 object where to store the result
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.addToRef = function (otherVector, result) {
  2839. result.x = this.x + otherVector.x;
  2840. result.y = this.y + otherVector.y;
  2841. result.z = this.z + otherVector.z;
  2842. return this;
  2843. };
  2844. /**
  2845. * Subtract the given vector from the current Vector3
  2846. * @param otherVector defines the second operand
  2847. * @returns the current updated Vector3
  2848. */
  2849. Vector3.prototype.subtractInPlace = function (otherVector) {
  2850. this.x -= otherVector.x;
  2851. this.y -= otherVector.y;
  2852. this.z -= otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2857. * @param otherVector defines the second operand
  2858. * @returns the resulting Vector3
  2859. */
  2860. Vector3.prototype.subtract = function (otherVector) {
  2861. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2862. };
  2863. /**
  2864. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2865. * @param otherVector defines the second operand
  2866. * @param result defines the Vector3 object where to store the result
  2867. * @returns the current Vector3
  2868. */
  2869. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2870. result.x = this.x - otherVector.x;
  2871. result.y = this.y - otherVector.y;
  2872. result.z = this.z - otherVector.z;
  2873. return this;
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2877. * @param x defines the x coordinate of the operand
  2878. * @param y defines the y coordinate of the operand
  2879. * @param z defines the z coordinate of the operand
  2880. * @returns the resulting Vector3
  2881. */
  2882. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2883. return new Vector3(this.x - x, this.y - y, this.z - z);
  2884. };
  2885. /**
  2886. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2894. result.x = this.x - x;
  2895. result.y = this.y - y;
  2896. result.z = this.z - z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2901. * @returns a new Vector3
  2902. */
  2903. Vector3.prototype.negate = function () {
  2904. return new Vector3(-this.x, -this.y, -this.z);
  2905. };
  2906. /**
  2907. * Multiplies the Vector3 coordinates by the float "scale"
  2908. * @param scale defines the multiplier factor
  2909. * @returns the current updated Vector3
  2910. */
  2911. Vector3.prototype.scaleInPlace = function (scale) {
  2912. this.x *= scale;
  2913. this.y *= scale;
  2914. this.z *= scale;
  2915. return this;
  2916. };
  2917. /**
  2918. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2919. * @param scale defines the multiplier factor
  2920. * @returns a new Vector3
  2921. */
  2922. Vector3.prototype.scale = function (scale) {
  2923. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2924. };
  2925. /**
  2926. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2927. * @param scale defines the multiplier factor
  2928. * @param result defines the Vector3 object where to store the result
  2929. * @returns the current Vector3
  2930. */
  2931. Vector3.prototype.scaleToRef = function (scale, result) {
  2932. result.x = this.x * scale;
  2933. result.y = this.y * scale;
  2934. result.z = this.z * scale;
  2935. return this;
  2936. };
  2937. /**
  2938. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2939. * @param scale defines the scale factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the unmodified current Vector3
  2942. */
  2943. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2944. result.x += this.x * scale;
  2945. result.y += this.y * scale;
  2946. result.z += this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2951. * @param otherVector defines the second operand
  2952. * @returns true if both vectors are equals
  2953. */
  2954. Vector3.prototype.equals = function (otherVector) {
  2955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2956. };
  2957. /**
  2958. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2959. * @param otherVector defines the second operand
  2960. * @param epsilon defines the minimal distance to define values as equals
  2961. * @returns true if both vectors are distant less than epsilon
  2962. */
  2963. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2964. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2965. 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);
  2966. };
  2967. /**
  2968. * Returns true if the current Vector3 coordinates equals the given floats
  2969. * @param x defines the x coordinate of the operand
  2970. * @param y defines the y coordinate of the operand
  2971. * @param z defines the z coordinate of the operand
  2972. * @returns true if both vectors are equals
  2973. */
  2974. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2975. return this.x === x && this.y === y && this.z === z;
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the given ones
  2979. * @param otherVector defines the second operand
  2980. * @returns the current updated Vector3
  2981. */
  2982. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2983. this.x *= otherVector.x;
  2984. this.y *= otherVector.y;
  2985. this.z *= otherVector.z;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2990. * @param otherVector defines the second operand
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.multiply = function (otherVector) {
  2994. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2995. };
  2996. /**
  2997. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2998. * @param otherVector defines the second operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3003. result.x = this.x * otherVector.x;
  3004. result.y = this.y * otherVector.y;
  3005. result.z = this.z * otherVector.z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3010. * @param x defines the x coordinate of the operand
  3011. * @param y defines the y coordinate of the operand
  3012. * @param z defines the z coordinate of the operand
  3013. * @returns the new Vector3
  3014. */
  3015. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3016. return new Vector3(this.x * x, this.y * y, this.z * z);
  3017. };
  3018. /**
  3019. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.divide = function (otherVector) {
  3024. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3025. };
  3026. /**
  3027. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.divideToRef = function (otherVector, result) {
  3033. result.x = this.x / otherVector.x;
  3034. result.y = this.y / otherVector.y;
  3035. result.z = this.z / otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones.
  3040. * @param otherVector defines the second operand
  3041. * @returns the current updated Vector3
  3042. */
  3043. Vector3.prototype.divideInPlace = function (otherVector) {
  3044. return this.divideToRef(otherVector, this);
  3045. };
  3046. /**
  3047. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3048. * @param other defines the second operand
  3049. * @returns the current updated Vector3
  3050. */
  3051. Vector3.prototype.minimizeInPlace = function (other) {
  3052. if (other.x < this.x)
  3053. this.x = other.x;
  3054. if (other.y < this.y)
  3055. this.y = other.y;
  3056. if (other.z < this.z)
  3057. this.z = other.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3062. * @param other defines the second operand
  3063. * @returns the current updated Vector3
  3064. */
  3065. Vector3.prototype.maximizeInPlace = function (other) {
  3066. if (other.x > this.x)
  3067. this.x = other.x;
  3068. if (other.y > this.y)
  3069. this.y = other.y;
  3070. if (other.z > this.z)
  3071. this.z = other.z;
  3072. return this;
  3073. };
  3074. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3075. /**
  3076. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3077. */
  3078. get: function () {
  3079. var absX = Math.abs(this.x);
  3080. var absY = Math.abs(this.y);
  3081. if (absX !== absY) {
  3082. return true;
  3083. }
  3084. var absZ = Math.abs(this.z);
  3085. if (absX !== absZ) {
  3086. return true;
  3087. }
  3088. if (absY !== absZ) {
  3089. return true;
  3090. }
  3091. return false;
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. // Properties
  3097. /**
  3098. * Gets the length of the Vector3
  3099. * @returns the length of the Vecto3
  3100. */
  3101. Vector3.prototype.length = function () {
  3102. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3103. };
  3104. /**
  3105. * Gets the squared length of the Vector3
  3106. * @returns squared length of the Vector3
  3107. */
  3108. Vector3.prototype.lengthSquared = function () {
  3109. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Normalize the current Vector3.
  3113. * Please note that this is an in place operation.
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.normalize = function () {
  3117. var len = this.length();
  3118. if (len === 0 || len === 1.0)
  3119. return this;
  3120. var num = 1.0 / len;
  3121. this.x *= num;
  3122. this.y *= num;
  3123. this.z *= num;
  3124. return this;
  3125. };
  3126. /**
  3127. * Normalize the current Vector3 to a new vector
  3128. * @returns the new Vector3
  3129. */
  3130. Vector3.prototype.normalizeToNew = function () {
  3131. var normalized = new Vector3(0, 0, 0);
  3132. this.normalizeToRef(normalized);
  3133. return normalized;
  3134. };
  3135. /**
  3136. * Normalize the current Vector3 to the reference
  3137. * @param reference define the Vector3 to update
  3138. * @returns the updated Vector3
  3139. */
  3140. Vector3.prototype.normalizeToRef = function (reference) {
  3141. var len = this.length();
  3142. if (len === 0 || len === 1.0) {
  3143. reference.set(this.x, this.y, this.z);
  3144. return reference;
  3145. }
  3146. var scale = 1.0 / len;
  3147. this.scaleToRef(scale, reference);
  3148. return reference;
  3149. };
  3150. /**
  3151. * Creates a new Vector3 copied from the current Vector3
  3152. * @returns the new Vector3
  3153. */
  3154. Vector3.prototype.clone = function () {
  3155. return new Vector3(this.x, this.y, this.z);
  3156. };
  3157. /**
  3158. * Copies the given vector coordinates to the current Vector3 ones
  3159. * @param source defines the source Vector3
  3160. * @returns the current updated Vector3
  3161. */
  3162. Vector3.prototype.copyFrom = function (source) {
  3163. this.x = source.x;
  3164. this.y = source.y;
  3165. this.z = source.z;
  3166. return this;
  3167. };
  3168. /**
  3169. * Copies the given floats to the current Vector3 coordinates
  3170. * @param x defines the x coordinate of the operand
  3171. * @param y defines the y coordinate of the operand
  3172. * @param z defines the z coordinate of the operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3176. this.x = x;
  3177. this.y = y;
  3178. this.z = z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Copies the given floats to the current Vector3 coordinates
  3183. * @param x defines the x coordinate of the operand
  3184. * @param y defines the y coordinate of the operand
  3185. * @param z defines the z coordinate of the operand
  3186. * @returns the current updated Vector3
  3187. */
  3188. Vector3.prototype.set = function (x, y, z) {
  3189. return this.copyFromFloats(x, y, z);
  3190. };
  3191. // Statics
  3192. /**
  3193. * Get the clip factor between two vectors
  3194. * @param vector0 defines the first operand
  3195. * @param vector1 defines the second operand
  3196. * @param axis defines the axis to use
  3197. * @param size defines the size along the axis
  3198. * @returns the clip factor
  3199. */
  3200. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3201. var d0 = Vector3.Dot(vector0, axis) - size;
  3202. var d1 = Vector3.Dot(vector1, axis) - size;
  3203. var s = d0 / (d0 - d1);
  3204. return s;
  3205. };
  3206. /**
  3207. * Get angle between two vectors
  3208. * @param vector0 angle between vector0 and vector1
  3209. * @param vector1 angle between vector0 and vector1
  3210. * @param normal direction of the normal
  3211. * @return the angle between vector0 and vector1
  3212. */
  3213. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3214. var v0 = vector0.clone().normalize();
  3215. var v1 = vector1.clone().normalize();
  3216. var dot = Vector3.Dot(v0, v1);
  3217. var n = Vector3.Cross(v0, v1);
  3218. if (Vector3.Dot(n, normal) > 0) {
  3219. return Math.acos(dot);
  3220. }
  3221. return -Math.acos(dot);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set from the index "offset" of the given array
  3225. * @param array defines the source array
  3226. * @param offset defines the offset in the source array
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.FromArray = function (array, offset) {
  3230. if (!offset) {
  3231. offset = 0;
  3232. }
  3233. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3237. * This function is deprecated. Use FromArray instead
  3238. * @param array defines the source array
  3239. * @param offset defines the offset in the source array
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.FromFloatArray = function (array, offset) {
  3243. return Vector3.FromArray(array, offset);
  3244. };
  3245. /**
  3246. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3247. * @param array defines the source array
  3248. * @param offset defines the offset in the source array
  3249. * @param result defines the Vector3 where to store the result
  3250. */
  3251. Vector3.FromArrayToRef = function (array, offset, result) {
  3252. result.x = array[offset];
  3253. result.y = array[offset + 1];
  3254. result.z = array[offset + 2];
  3255. };
  3256. /**
  3257. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3258. * This function is deprecated. Use FromArrayToRef instead.
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3264. return Vector3.FromArrayToRef(array, offset, result);
  3265. };
  3266. /**
  3267. * Sets the given vector "result" with the given floats.
  3268. * @param x defines the x coordinate of the source
  3269. * @param y defines the y coordinate of the source
  3270. * @param z defines the z coordinate of the source
  3271. * @param result defines the Vector3 where to store the result
  3272. */
  3273. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3274. result.x = x;
  3275. result.y = y;
  3276. result.z = z;
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3280. * @returns a new empty Vector3
  3281. */
  3282. Vector3.Zero = function () {
  3283. return new Vector3(0.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3287. * @returns a new unit Vector3
  3288. */
  3289. Vector3.One = function () {
  3290. return new Vector3(1.0, 1.0, 1.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3294. * @returns a new up Vector3
  3295. */
  3296. Vector3.Up = function () {
  3297. return new Vector3(0.0, 1.0, 0.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3301. * @returns a new forward Vector3
  3302. */
  3303. Vector3.Forward = function () {
  3304. return new Vector3(0.0, 0.0, 1.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3308. * @returns a new right Vector3
  3309. */
  3310. Vector3.Right = function () {
  3311. return new Vector3(1.0, 0.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3315. * @returns a new left Vector3
  3316. */
  3317. Vector3.Left = function () {
  3318. return new Vector3(-1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3322. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3323. * @param vector defines the Vector3 to transform
  3324. * @param transformation defines the transformation matrix
  3325. * @returns the transformed Vector3
  3326. */
  3327. Vector3.TransformCoordinates = function (vector, transformation) {
  3328. var result = Vector3.Zero();
  3329. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3330. return result;
  3331. };
  3332. /**
  3333. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3334. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3335. * @param vector defines the Vector3 to transform
  3336. * @param transformation defines the transformation matrix
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3340. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3341. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3342. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3343. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3344. result.x = x / w;
  3345. result.y = y / w;
  3346. result.z = z / w;
  3347. };
  3348. /**
  3349. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3350. * This method computes tranformed coordinates only, not transformed direction vectors
  3351. * @param x define the x coordinate of the source vector
  3352. * @param y define the y coordinate of the source vector
  3353. * @param z define the z coordinate of the source vector
  3354. * @param transformation defines the transformation matrix
  3355. * @param result defines the Vector3 where to store the result
  3356. */
  3357. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3358. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3359. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3360. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3361. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3362. result.x = rx / rw;
  3363. result.y = ry / rw;
  3364. result.z = rz / rw;
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3368. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.TransformNormal = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformNormalToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3380. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3389. result.x = x;
  3390. result.y = y;
  3391. result.z = z;
  3392. };
  3393. /**
  3394. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3404. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3405. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3409. * @param value1 defines the first control point
  3410. * @param value2 defines the second control point
  3411. * @param value3 defines the third control point
  3412. * @param value4 defines the fourth control point
  3413. * @param amount defines the amount on the spline to use
  3414. * @returns the new Vector3
  3415. */
  3416. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3417. var squared = amount * amount;
  3418. var cubed = amount * squared;
  3419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3425. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3426. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3427. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3428. return new Vector3(x, y, z);
  3429. };
  3430. /**
  3431. * 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"
  3432. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3433. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3434. * @param value defines the current value
  3435. * @param min defines the lower range value
  3436. * @param max defines the upper range value
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Clamp = function (value, min, max) {
  3440. var x = value.x;
  3441. x = (x > max.x) ? max.x : x;
  3442. x = (x < min.x) ? min.x : x;
  3443. var y = value.y;
  3444. y = (y > max.y) ? max.y : y;
  3445. y = (y < min.y) ? min.y : y;
  3446. var z = value.z;
  3447. z = (z > max.z) ? max.z : z;
  3448. z = (z < min.z) ? min.z : z;
  3449. return new Vector3(x, y, z);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3453. * @param value1 defines the first control point
  3454. * @param tangent1 defines the first tangent vector
  3455. * @param value2 defines the second control point
  3456. * @param tangent2 defines the second tangent vector
  3457. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3461. var squared = amount * amount;
  3462. var cubed = amount * squared;
  3463. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3464. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3465. var part3 = (cubed - (2.0 * squared)) + amount;
  3466. var part4 = cubed - squared;
  3467. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3468. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3469. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3470. return new Vector3(x, y, z);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3474. * @param start defines the start value
  3475. * @param end defines the end value
  3476. * @param amount max defines amount between both (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Lerp = function (start, end, amount) {
  3480. var result = new Vector3(0, 0, 0);
  3481. Vector3.LerpToRef(start, end, amount, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3486. * @param start defines the start value
  3487. * @param end defines the end value
  3488. * @param amount max defines amount between both (between 0 and 1)
  3489. * @param result defines the Vector3 where to store the result
  3490. */
  3491. Vector3.LerpToRef = function (start, end, amount, result) {
  3492. result.x = start.x + ((end.x - start.x) * amount);
  3493. result.y = start.y + ((end.y - start.y) * amount);
  3494. result.z = start.z + ((end.z - start.z) * amount);
  3495. };
  3496. /**
  3497. * Returns the dot product (float) between the vectors "left" and "right"
  3498. * @param left defines the left operand
  3499. * @param right defines the right operand
  3500. * @returns the dot product
  3501. */
  3502. Vector3.Dot = function (left, right) {
  3503. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3507. * The cross product is then orthogonal to both "left" and "right"
  3508. * @param left defines the left operand
  3509. * @param right defines the right operand
  3510. * @returns the cross product
  3511. */
  3512. Vector3.Cross = function (left, right) {
  3513. var result = Vector3.Zero();
  3514. Vector3.CrossToRef(left, right, result);
  3515. return result;
  3516. };
  3517. /**
  3518. * Sets the given vector "result" with the cross product of "left" and "right"
  3519. * The cross product is then orthogonal to both "left" and "right"
  3520. * @param left defines the left operand
  3521. * @param right defines the right operand
  3522. * @param result defines the Vector3 where to store the result
  3523. */
  3524. Vector3.CrossToRef = function (left, right, result) {
  3525. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3526. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3527. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3528. result.copyFrom(MathTmp.Vector3[0]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 as the normalization of the given vector
  3532. * @param vector defines the Vector3 to normalize
  3533. * @returns the new Vector3
  3534. */
  3535. Vector3.Normalize = function (vector) {
  3536. var result = Vector3.Zero();
  3537. Vector3.NormalizeToRef(vector, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the given vector "result" with the normalization of the given first vector
  3542. * @param vector defines the Vector3 to normalize
  3543. * @param result defines the Vector3 where to store the result
  3544. */
  3545. Vector3.NormalizeToRef = function (vector, result) {
  3546. result.copyFrom(vector);
  3547. result.normalize();
  3548. };
  3549. /**
  3550. * Project a Vector3 onto screen space
  3551. * @param vector defines the Vector3 to project
  3552. * @param world defines the world matrix to use
  3553. * @param transform defines the transform (view x projection) matrix to use
  3554. * @param viewport defines the screen viewport to use
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Project = function (vector, world, transform, viewport) {
  3558. var cw = viewport.width;
  3559. var ch = viewport.height;
  3560. var cx = viewport.x;
  3561. var cy = viewport.y;
  3562. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3563. 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);
  3564. var matrix = MathTmp.Matrix[0];
  3565. world.multiplyToRef(transform, matrix);
  3566. matrix.multiplyToRef(viewportMatrix, matrix);
  3567. return Vector3.TransformCoordinates(vector, matrix);
  3568. };
  3569. /**
  3570. * Unproject from screen space to object space
  3571. * @param source defines the screen space Vector3 to use
  3572. * @param viewportWidth defines the current width of the viewport
  3573. * @param viewportHeight defines the current height of the viewport
  3574. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3575. * @param transform defines the transform (view x projection) matrix to use
  3576. * @returns the new Vector3
  3577. */
  3578. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3579. var matrix = MathTmp.Matrix[0];
  3580. world.multiplyToRef(transform, matrix);
  3581. matrix.invert();
  3582. source.x = source.x / viewportWidth * 2 - 1;
  3583. source.y = -(source.y / viewportHeight * 2 - 1);
  3584. var vector = Vector3.TransformCoordinates(source, matrix);
  3585. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3586. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3587. vector = vector.scale(1.0 / num);
  3588. }
  3589. return vector;
  3590. };
  3591. /**
  3592. * Unproject from screen space to object space
  3593. * @param source defines the screen space Vector3 to use
  3594. * @param viewportWidth defines the current width of the viewport
  3595. * @param viewportHeight defines the current height of the viewport
  3596. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3597. * @param view defines the view matrix to use
  3598. * @param projection defines the projection matrix to use
  3599. * @returns the new Vector3
  3600. */
  3601. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3602. var result = Vector3.Zero();
  3603. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3604. return result;
  3605. };
  3606. /**
  3607. * Unproject from screen space to object space
  3608. * @param source defines the screen space Vector3 to use
  3609. * @param viewportWidth defines the current width of the viewport
  3610. * @param viewportHeight defines the current height of the viewport
  3611. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3612. * @param view defines the view matrix to use
  3613. * @param projection defines the projection matrix to use
  3614. * @param result defines the Vector3 where to store the result
  3615. */
  3616. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3617. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3618. };
  3619. /**
  3620. * Unproject from screen space to object space
  3621. * @param sourceX defines the screen space x coordinate to use
  3622. * @param sourceY defines the screen space y coordinate to use
  3623. * @param sourceZ defines the screen space z coordinate to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @param result defines the Vector3 where to store the result
  3630. */
  3631. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3632. var matrix = MathTmp.Matrix[0];
  3633. world.multiplyToRef(view, matrix);
  3634. matrix.multiplyToRef(projection, matrix);
  3635. matrix.invert();
  3636. var screenSource = MathTmp.Vector3[0];
  3637. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3638. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3639. screenSource.z = 2 * sourceZ - 1.0;
  3640. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3641. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3642. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3643. result.scaleInPlace(1.0 / num);
  3644. }
  3645. };
  3646. /**
  3647. * Gets the minimal coordinate values between two Vector3
  3648. * @param left defines the first operand
  3649. * @param right defines the second operand
  3650. * @returns the new Vector3
  3651. */
  3652. Vector3.Minimize = function (left, right) {
  3653. var min = left.clone();
  3654. min.minimizeInPlace(right);
  3655. return min;
  3656. };
  3657. /**
  3658. * Gets the maximal coordinate values between two Vector3
  3659. * @param left defines the first operand
  3660. * @param right defines the second operand
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Maximize = function (left, right) {
  3664. var max = left.clone();
  3665. max.maximizeInPlace(right);
  3666. return max;
  3667. };
  3668. /**
  3669. * Returns the distance between the vectors "value1" and "value2"
  3670. * @param value1 defines the first operand
  3671. * @param value2 defines the second operand
  3672. * @returns the distance
  3673. */
  3674. Vector3.Distance = function (value1, value2) {
  3675. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3676. };
  3677. /**
  3678. * Returns the squared distance between the vectors "value1" and "value2"
  3679. * @param value1 defines the first operand
  3680. * @param value2 defines the second operand
  3681. * @returns the squared distance
  3682. */
  3683. Vector3.DistanceSquared = function (value1, value2) {
  3684. var x = value1.x - value2.x;
  3685. var y = value1.y - value2.y;
  3686. var z = value1.z - value2.z;
  3687. return (x * x) + (y * y) + (z * z);
  3688. };
  3689. /**
  3690. * Returns a new Vector3 located at the center between "value1" and "value2"
  3691. * @param value1 defines the first operand
  3692. * @param value2 defines the second operand
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Center = function (value1, value2) {
  3696. var center = value1.add(value2);
  3697. center.scaleInPlace(0.5);
  3698. return center;
  3699. };
  3700. /**
  3701. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3702. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3703. * to something in order to rotate it from its local system to the given target system
  3704. * Note: axis1, axis2 and axis3 are normalized during this operation
  3705. * @param axis1 defines the first axis
  3706. * @param axis2 defines the second axis
  3707. * @param axis3 defines the third axis
  3708. * @returns a new Vector3
  3709. */
  3710. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3711. var rotation = Vector3.Zero();
  3712. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3713. return rotation;
  3714. };
  3715. /**
  3716. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3717. * @param axis1 defines the first axis
  3718. * @param axis2 defines the second axis
  3719. * @param axis3 defines the third axis
  3720. * @param ref defines the Vector3 where to store the result
  3721. */
  3722. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3723. var quat = MathTmp.Quaternion[0];
  3724. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3725. quat.toEulerAnglesToRef(ref);
  3726. };
  3727. return Vector3;
  3728. }());
  3729. BABYLON.Vector3 = Vector3;
  3730. //Vector4 class created for EulerAngle class conversion to Quaternion
  3731. var Vector4 = /** @class */ (function () {
  3732. /**
  3733. * Creates a Vector4 object from the given floats.
  3734. */
  3735. function Vector4(x, y, z, w) {
  3736. this.x = x;
  3737. this.y = y;
  3738. this.z = z;
  3739. this.w = w;
  3740. }
  3741. /**
  3742. * Returns the string with the Vector4 coordinates.
  3743. */
  3744. Vector4.prototype.toString = function () {
  3745. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3746. };
  3747. /**
  3748. * Returns the string "Vector4".
  3749. */
  3750. Vector4.prototype.getClassName = function () {
  3751. return "Vector4";
  3752. };
  3753. /**
  3754. * Returns the Vector4 hash code.
  3755. */
  3756. Vector4.prototype.getHashCode = function () {
  3757. var hash = this.x || 0;
  3758. hash = (hash * 397) ^ (this.y || 0);
  3759. hash = (hash * 397) ^ (this.z || 0);
  3760. hash = (hash * 397) ^ (this.w || 0);
  3761. return hash;
  3762. };
  3763. // Operators
  3764. /**
  3765. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3766. */
  3767. Vector4.prototype.asArray = function () {
  3768. var result = new Array();
  3769. this.toArray(result, 0);
  3770. return result;
  3771. };
  3772. /**
  3773. * Populates the given array from the given index with the Vector4 coordinates.
  3774. * Returns the Vector4.
  3775. */
  3776. Vector4.prototype.toArray = function (array, index) {
  3777. if (index === undefined) {
  3778. index = 0;
  3779. }
  3780. array[index] = this.x;
  3781. array[index + 1] = this.y;
  3782. array[index + 2] = this.z;
  3783. array[index + 3] = this.w;
  3784. return this;
  3785. };
  3786. /**
  3787. * Adds the given vector to the current Vector4.
  3788. * Returns the updated Vector4.
  3789. */
  3790. Vector4.prototype.addInPlace = function (otherVector) {
  3791. this.x += otherVector.x;
  3792. this.y += otherVector.y;
  3793. this.z += otherVector.z;
  3794. this.w += otherVector.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3799. */
  3800. Vector4.prototype.add = function (otherVector) {
  3801. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3802. };
  3803. /**
  3804. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3805. * Returns the current Vector4.
  3806. */
  3807. Vector4.prototype.addToRef = function (otherVector, result) {
  3808. result.x = this.x + otherVector.x;
  3809. result.y = this.y + otherVector.y;
  3810. result.z = this.z + otherVector.z;
  3811. result.w = this.w + otherVector.w;
  3812. return this;
  3813. };
  3814. /**
  3815. * Subtract in place the given vector from the current Vector4.
  3816. * Returns the updated Vector4.
  3817. */
  3818. Vector4.prototype.subtractInPlace = function (otherVector) {
  3819. this.x -= otherVector.x;
  3820. this.y -= otherVector.y;
  3821. this.z -= otherVector.z;
  3822. this.w -= otherVector.w;
  3823. return this;
  3824. };
  3825. /**
  3826. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3827. */
  3828. Vector4.prototype.subtract = function (otherVector) {
  3829. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3830. };
  3831. /**
  3832. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3833. * Returns the current Vector4.
  3834. */
  3835. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3836. result.x = this.x - otherVector.x;
  3837. result.y = this.y - otherVector.y;
  3838. result.z = this.z - otherVector.z;
  3839. result.w = this.w - otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3844. */
  3845. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3846. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3847. };
  3848. /**
  3849. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3853. result.x = this.x - x;
  3854. result.y = this.y - y;
  3855. result.z = this.z - z;
  3856. result.w = this.w - w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3861. */
  3862. Vector4.prototype.negate = function () {
  3863. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3864. };
  3865. /**
  3866. * Multiplies the current Vector4 coordinates by scale (float).
  3867. * Returns the updated Vector4.
  3868. */
  3869. Vector4.prototype.scaleInPlace = function (scale) {
  3870. this.x *= scale;
  3871. this.y *= scale;
  3872. this.z *= scale;
  3873. this.w *= scale;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3878. */
  3879. Vector4.prototype.scale = function (scale) {
  3880. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.scaleToRef = function (scale, result) {
  3887. result.x = this.x * scale;
  3888. result.y = this.y * scale;
  3889. result.z = this.z * scale;
  3890. result.w = this.w * scale;
  3891. return this;
  3892. };
  3893. /**
  3894. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3895. * @param scale defines the scale factor
  3896. * @param result defines the Vector4 object where to store the result
  3897. * @returns the unmodified current Vector4
  3898. */
  3899. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3900. result.x += this.x * scale;
  3901. result.y += this.y * scale;
  3902. result.z += this.z * scale;
  3903. result.w += this.w * scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3908. */
  3909. Vector4.prototype.equals = function (otherVector) {
  3910. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3911. };
  3912. /**
  3913. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3914. */
  3915. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3916. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3917. return otherVector
  3918. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3919. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3920. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3921. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3922. };
  3923. /**
  3924. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3925. */
  3926. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3927. return this.x === x && this.y === y && this.z === z && this.w === w;
  3928. };
  3929. /**
  3930. * Multiplies in place the current Vector4 by the given one.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3934. this.x *= otherVector.x;
  3935. this.y *= otherVector.y;
  3936. this.z *= otherVector.z;
  3937. this.w *= otherVector.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3942. */
  3943. Vector4.prototype.multiply = function (otherVector) {
  3944. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3945. };
  3946. /**
  3947. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3948. * Returns the current Vector4.
  3949. */
  3950. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3951. result.x = this.x * otherVector.x;
  3952. result.y = this.y * otherVector.y;
  3953. result.z = this.z * otherVector.z;
  3954. result.w = this.w * otherVector.w;
  3955. return this;
  3956. };
  3957. /**
  3958. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3961. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3965. */
  3966. Vector4.prototype.divide = function (otherVector) {
  3967. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3968. };
  3969. /**
  3970. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.divideToRef = function (otherVector, result) {
  3974. result.x = this.x / otherVector.x;
  3975. result.y = this.y / otherVector.y;
  3976. result.z = this.z / otherVector.z;
  3977. result.w = this.w / otherVector.w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Divides the current Vector3 coordinates by the given ones.
  3982. * @returns the updated Vector3.
  3983. */
  3984. Vector4.prototype.divideInPlace = function (otherVector) {
  3985. return this.divideToRef(otherVector, this);
  3986. };
  3987. /**
  3988. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3989. * @param other defines the second operand
  3990. * @returns the current updated Vector4
  3991. */
  3992. Vector4.prototype.minimizeInPlace = function (other) {
  3993. if (other.x < this.x)
  3994. this.x = other.x;
  3995. if (other.y < this.y)
  3996. this.y = other.y;
  3997. if (other.z < this.z)
  3998. this.z = other.z;
  3999. if (other.w < this.w)
  4000. this.w = other.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4005. * @param other defines the second operand
  4006. * @returns the current updated Vector4
  4007. */
  4008. Vector4.prototype.maximizeInPlace = function (other) {
  4009. if (other.x > this.x)
  4010. this.x = other.x;
  4011. if (other.y > this.y)
  4012. this.y = other.y;
  4013. if (other.z > this.z)
  4014. this.z = other.z;
  4015. if (other.w > this.w)
  4016. this.w = other.w;
  4017. return this;
  4018. };
  4019. // Properties
  4020. /**
  4021. * Returns the Vector4 length (float).
  4022. */
  4023. Vector4.prototype.length = function () {
  4024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4025. };
  4026. /**
  4027. * Returns the Vector4 squared length (float).
  4028. */
  4029. Vector4.prototype.lengthSquared = function () {
  4030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4031. };
  4032. // Methods
  4033. /**
  4034. * Normalizes in place the Vector4.
  4035. * Returns the updated Vector4.
  4036. */
  4037. Vector4.prototype.normalize = function () {
  4038. var len = this.length();
  4039. if (len === 0)
  4040. return this;
  4041. var num = 1.0 / len;
  4042. this.x *= num;
  4043. this.y *= num;
  4044. this.z *= num;
  4045. this.w *= num;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4050. */
  4051. Vector4.prototype.toVector3 = function () {
  4052. return new Vector3(this.x, this.y, this.z);
  4053. };
  4054. /**
  4055. * Returns a new Vector4 copied from the current one.
  4056. */
  4057. Vector4.prototype.clone = function () {
  4058. return new Vector4(this.x, this.y, this.z, this.w);
  4059. };
  4060. /**
  4061. * Updates the current Vector4 with the given one coordinates.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.copyFrom = function (source) {
  4065. this.x = source.x;
  4066. this.y = source.y;
  4067. this.z = source.z;
  4068. this.w = source.w;
  4069. return this;
  4070. };
  4071. /**
  4072. * Updates the current Vector4 coordinates with the given floats.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4076. this.x = x;
  4077. this.y = y;
  4078. this.z = z;
  4079. this.w = w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Updates the current Vector4 coordinates with the given floats.
  4084. * Returns the updated Vector4.
  4085. */
  4086. Vector4.prototype.set = function (x, y, z, w) {
  4087. return this.copyFromFloats(x, y, z, w);
  4088. };
  4089. // Statics
  4090. /**
  4091. * Returns a new Vector4 set from the starting index of the given array.
  4092. */
  4093. Vector4.FromArray = function (array, offset) {
  4094. if (!offset) {
  4095. offset = 0;
  4096. }
  4097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4098. };
  4099. /**
  4100. * Updates the given vector "result" from the starting index of the given array.
  4101. */
  4102. Vector4.FromArrayToRef = function (array, offset, result) {
  4103. result.x = array[offset];
  4104. result.y = array[offset + 1];
  4105. result.z = array[offset + 2];
  4106. result.w = array[offset + 3];
  4107. };
  4108. /**
  4109. * Updates the given vector "result" from the starting index of the given Float32Array.
  4110. */
  4111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4112. Vector4.FromArrayToRef(array, offset, result);
  4113. };
  4114. /**
  4115. * Updates the given vector "result" coordinates from the given floats.
  4116. */
  4117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4118. result.x = x;
  4119. result.y = y;
  4120. result.z = z;
  4121. result.w = w;
  4122. };
  4123. /**
  4124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4125. */
  4126. Vector4.Zero = function () {
  4127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4128. };
  4129. /**
  4130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4131. */
  4132. Vector4.One = function () {
  4133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4134. };
  4135. /**
  4136. * Returns a new normalized Vector4 from the given one.
  4137. */
  4138. Vector4.Normalize = function (vector) {
  4139. var result = Vector4.Zero();
  4140. Vector4.NormalizeToRef(vector, result);
  4141. return result;
  4142. };
  4143. /**
  4144. * Updates the given vector "result" from the normalization of the given one.
  4145. */
  4146. Vector4.NormalizeToRef = function (vector, result) {
  4147. result.copyFrom(vector);
  4148. result.normalize();
  4149. };
  4150. Vector4.Minimize = function (left, right) {
  4151. var min = left.clone();
  4152. min.minimizeInPlace(right);
  4153. return min;
  4154. };
  4155. Vector4.Maximize = function (left, right) {
  4156. var max = left.clone();
  4157. max.maximizeInPlace(right);
  4158. return max;
  4159. };
  4160. /**
  4161. * Returns the distance (float) between the vectors "value1" and "value2".
  4162. */
  4163. Vector4.Distance = function (value1, value2) {
  4164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4165. };
  4166. /**
  4167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4168. */
  4169. Vector4.DistanceSquared = function (value1, value2) {
  4170. var x = value1.x - value2.x;
  4171. var y = value1.y - value2.y;
  4172. var z = value1.z - value2.z;
  4173. var w = value1.w - value2.w;
  4174. return (x * x) + (y * y) + (z * z) + (w * w);
  4175. };
  4176. /**
  4177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4178. */
  4179. Vector4.Center = function (value1, value2) {
  4180. var center = value1.add(value2);
  4181. center.scaleInPlace(0.5);
  4182. return center;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4186. * This methods computes transformed normalized direction vectors only.
  4187. */
  4188. Vector4.TransformNormal = function (vector, transformation) {
  4189. var result = Vector4.Zero();
  4190. Vector4.TransformNormalToRef(vector, transformation, result);
  4191. return result;
  4192. };
  4193. /**
  4194. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4195. * This methods computes transformed normalized direction vectors only.
  4196. */
  4197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4201. result.x = x;
  4202. result.y = y;
  4203. result.z = z;
  4204. result.w = vector.w;
  4205. };
  4206. /**
  4207. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4208. * This methods computes transformed normalized direction vectors only.
  4209. */
  4210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4214. result.w = w;
  4215. };
  4216. return Vector4;
  4217. }());
  4218. BABYLON.Vector4 = Vector4;
  4219. var Size = /** @class */ (function () {
  4220. /**
  4221. * Creates a Size object from the given width and height (floats).
  4222. */
  4223. function Size(width, height) {
  4224. this.width = width;
  4225. this.height = height;
  4226. }
  4227. // Returns a string with the Size width and height.
  4228. Size.prototype.toString = function () {
  4229. return "{W: " + this.width + ", H: " + this.height + "}";
  4230. };
  4231. /**
  4232. * Returns the string "Size"
  4233. */
  4234. Size.prototype.getClassName = function () {
  4235. return "Size";
  4236. };
  4237. /**
  4238. * Returns the Size hash code.
  4239. */
  4240. Size.prototype.getHashCode = function () {
  4241. var hash = this.width || 0;
  4242. hash = (hash * 397) ^ (this.height || 0);
  4243. return hash;
  4244. };
  4245. /**
  4246. * Updates the current size from the given one.
  4247. * Returns the updated Size.
  4248. */
  4249. Size.prototype.copyFrom = function (src) {
  4250. this.width = src.width;
  4251. this.height = src.height;
  4252. };
  4253. /**
  4254. * Updates in place the current Size from the given floats.
  4255. * Returns the updated Size.
  4256. */
  4257. Size.prototype.copyFromFloats = function (width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. return this;
  4261. };
  4262. /**
  4263. * Updates in place the current Size from the given floats.
  4264. * Returns the updated Size.
  4265. */
  4266. Size.prototype.set = function (width, height) {
  4267. return this.copyFromFloats(width, height);
  4268. };
  4269. /**
  4270. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4271. */
  4272. Size.prototype.multiplyByFloats = function (w, h) {
  4273. return new Size(this.width * w, this.height * h);
  4274. };
  4275. /**
  4276. * Returns a new Size copied from the given one.
  4277. */
  4278. Size.prototype.clone = function () {
  4279. return new Size(this.width, this.height);
  4280. };
  4281. /**
  4282. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4283. */
  4284. Size.prototype.equals = function (other) {
  4285. if (!other) {
  4286. return false;
  4287. }
  4288. return (this.width === other.width) && (this.height === other.height);
  4289. };
  4290. Object.defineProperty(Size.prototype, "surface", {
  4291. /**
  4292. * Returns the surface of the Size : width * height (float).
  4293. */
  4294. get: function () {
  4295. return this.width * this.height;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. /**
  4301. * Returns a new Size set to (0.0, 0.0)
  4302. */
  4303. Size.Zero = function () {
  4304. return new Size(0.0, 0.0);
  4305. };
  4306. /**
  4307. * Returns a new Size set as the addition result of the current Size and the given one.
  4308. */
  4309. Size.prototype.add = function (otherSize) {
  4310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4311. return r;
  4312. };
  4313. /**
  4314. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4315. */
  4316. Size.prototype.subtract = function (otherSize) {
  4317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4322. */
  4323. Size.Lerp = function (start, end, amount) {
  4324. var w = start.width + ((end.width - start.width) * amount);
  4325. var h = start.height + ((end.height - start.height) * amount);
  4326. return new Size(w, h);
  4327. };
  4328. return Size;
  4329. }());
  4330. BABYLON.Size = Size;
  4331. /**
  4332. * Class used to store quaternion data
  4333. * @see https://en.wikipedia.org/wiki/Quaternion
  4334. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4335. */
  4336. var Quaternion = /** @class */ (function () {
  4337. /**
  4338. * Creates a new Quaternion from the given floats
  4339. * @param x defines the first component (0 by default)
  4340. * @param y defines the second component (0 by default)
  4341. * @param z defines the third component (0 by default)
  4342. * @param w defines the fourth component (1.0 by default)
  4343. */
  4344. function Quaternion(
  4345. /** defines the first component (0 by default) */
  4346. x,
  4347. /** defines the second component (0 by default) */
  4348. y,
  4349. /** defines the third component (0 by default) */
  4350. z,
  4351. /** defines the fourth component (1.0 by default) */
  4352. w) {
  4353. if (x === void 0) { x = 0.0; }
  4354. if (y === void 0) { y = 0.0; }
  4355. if (z === void 0) { z = 0.0; }
  4356. if (w === void 0) { w = 1.0; }
  4357. this.x = x;
  4358. this.y = y;
  4359. this.z = z;
  4360. this.w = w;
  4361. }
  4362. /**
  4363. * Gets a string representation for the current quaternion
  4364. * @returns a string with the Quaternion coordinates
  4365. */
  4366. Quaternion.prototype.toString = function () {
  4367. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4368. };
  4369. /**
  4370. * Gets the class name of the quaternion
  4371. * @returns the string "Quaternion"
  4372. */
  4373. Quaternion.prototype.getClassName = function () {
  4374. return "Quaternion";
  4375. };
  4376. /**
  4377. * Gets a hash code for this quaternion
  4378. * @returns the quaternion hash code
  4379. */
  4380. Quaternion.prototype.getHashCode = function () {
  4381. var hash = this.x || 0;
  4382. hash = (hash * 397) ^ (this.y || 0);
  4383. hash = (hash * 397) ^ (this.z || 0);
  4384. hash = (hash * 397) ^ (this.w || 0);
  4385. return hash;
  4386. };
  4387. /**
  4388. * Copy the quaternion to an array
  4389. * @returns a new array populated with 4 elements from the quaternion coordinates
  4390. */
  4391. Quaternion.prototype.asArray = function () {
  4392. return [this.x, this.y, this.z, this.w];
  4393. };
  4394. /**
  4395. * Check if two quaternions are equals
  4396. * @param otherQuaternion defines the second operand
  4397. * @return true if the current quaternion and the given one coordinates are strictly equals
  4398. */
  4399. Quaternion.prototype.equals = function (otherQuaternion) {
  4400. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4401. };
  4402. /**
  4403. * Clone the current quaternion
  4404. * @returns a new quaternion copied from the current one
  4405. */
  4406. Quaternion.prototype.clone = function () {
  4407. return new Quaternion(this.x, this.y, this.z, this.w);
  4408. };
  4409. /**
  4410. * Copy a quaternion to the current one
  4411. * @param other defines the other quaternion
  4412. * @returns the updated current quaternion
  4413. */
  4414. Quaternion.prototype.copyFrom = function (other) {
  4415. this.x = other.x;
  4416. this.y = other.y;
  4417. this.z = other.z;
  4418. this.w = other.w;
  4419. return this;
  4420. };
  4421. /**
  4422. * Updates the current quaternion with the given float coordinates
  4423. * @param x defines the x coordinate
  4424. * @param y defines the y coordinate
  4425. * @param z defines the z coordinate
  4426. * @param w defines the w coordinate
  4427. * @returns the updated current quaternion
  4428. */
  4429. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4430. this.x = x;
  4431. this.y = y;
  4432. this.z = z;
  4433. this.w = w;
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion from the given float coordinates
  4438. * @param x defines the x coordinate
  4439. * @param y defines the y coordinate
  4440. * @param z defines the z coordinate
  4441. * @param w defines the w coordinate
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.set = function (x, y, z, w) {
  4445. return this.copyFromFloats(x, y, z, w);
  4446. };
  4447. /**
  4448. * Adds two quaternions
  4449. * @param other defines the second operand
  4450. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4451. */
  4452. Quaternion.prototype.add = function (other) {
  4453. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4454. };
  4455. /**
  4456. * Add a quaternion to the current one
  4457. * @param other defines the quaternion to add
  4458. * @returns the current quaternion
  4459. */
  4460. Quaternion.prototype.addInPlace = function (other) {
  4461. this.x += other.x;
  4462. this.y += other.y;
  4463. this.z += other.z;
  4464. this.w += other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Subtract two quaternions
  4469. * @param other defines the second operand
  4470. * @returns a new quaternion as the subtraction result of the given one from the current one
  4471. */
  4472. Quaternion.prototype.subtract = function (other) {
  4473. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4474. };
  4475. /**
  4476. * Multiplies the current quaternion by a scale factor
  4477. * @param value defines the scale factor
  4478. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4479. */
  4480. Quaternion.prototype.scale = function (value) {
  4481. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4482. };
  4483. /**
  4484. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4485. * @param scale defines the scale factor
  4486. * @param result defines the Quaternion object where to store the result
  4487. * @returns the unmodified current quaternion
  4488. */
  4489. Quaternion.prototype.scaleToRef = function (scale, result) {
  4490. result.x = this.x * scale;
  4491. result.y = this.y * scale;
  4492. result.z = this.z * scale;
  4493. result.w = this.w * scale;
  4494. return this;
  4495. };
  4496. /**
  4497. * Multiplies in place the current quaternion by a scale factor
  4498. * @param value defines the scale factor
  4499. * @returns the current modified quaternion
  4500. */
  4501. Quaternion.prototype.scaleInPlace = function (value) {
  4502. this.x *= value;
  4503. this.y *= value;
  4504. this.z *= value;
  4505. this.w *= value;
  4506. return this;
  4507. };
  4508. /**
  4509. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4510. * @param scale defines the scale factor
  4511. * @param result defines the Quaternion object where to store the result
  4512. * @returns the unmodified current quaternion
  4513. */
  4514. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4515. result.x += this.x * scale;
  4516. result.y += this.y * scale;
  4517. result.z += this.z * scale;
  4518. result.w += this.w * scale;
  4519. return this;
  4520. };
  4521. /**
  4522. * Multiplies two quaternions
  4523. * @param q1 defines the second operand
  4524. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4525. */
  4526. Quaternion.prototype.multiply = function (q1) {
  4527. var result = new Quaternion(0, 0, 0, 1.0);
  4528. this.multiplyToRef(q1, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4533. * @param q1 defines the second operand
  4534. * @param result defines the target quaternion
  4535. * @returns the current quaternion
  4536. */
  4537. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4538. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4539. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4540. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4541. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4542. result.copyFromFloats(x, y, z, w);
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @returns the currentupdated quaternion
  4549. */
  4550. Quaternion.prototype.multiplyInPlace = function (q1) {
  4551. this.multiplyToRef(q1, this);
  4552. return this;
  4553. };
  4554. /**
  4555. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4556. * @param ref defines the target quaternion
  4557. * @returns the current quaternion
  4558. */
  4559. Quaternion.prototype.conjugateToRef = function (ref) {
  4560. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4561. return this;
  4562. };
  4563. /**
  4564. * Conjugates in place (1-q) the current quaternion
  4565. * @returns the current updated quaternion
  4566. */
  4567. Quaternion.prototype.conjugateInPlace = function () {
  4568. this.x *= -1;
  4569. this.y *= -1;
  4570. this.z *= -1;
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates in place (1-q) the current quaternion
  4575. * @returns a new quaternion
  4576. */
  4577. Quaternion.prototype.conjugate = function () {
  4578. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4579. return result;
  4580. };
  4581. /**
  4582. * Gets length of current quaternion
  4583. * @returns the quaternion length (float)
  4584. */
  4585. Quaternion.prototype.length = function () {
  4586. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4587. };
  4588. /**
  4589. * Normalize in place the current quaternion
  4590. * @returns the current updated quaternion
  4591. */
  4592. Quaternion.prototype.normalize = function () {
  4593. var length = 1.0 / this.length();
  4594. this.x *= length;
  4595. this.y *= length;
  4596. this.z *= length;
  4597. this.w *= length;
  4598. return this;
  4599. };
  4600. /**
  4601. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4602. * @param order is a reserved parameter and is ignore for now
  4603. * @returns a new Vector3 containing the Euler angles
  4604. */
  4605. Quaternion.prototype.toEulerAngles = function (order) {
  4606. if (order === void 0) { order = "YZX"; }
  4607. var result = Vector3.Zero();
  4608. this.toEulerAnglesToRef(result, order);
  4609. return result;
  4610. };
  4611. /**
  4612. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4613. * @param result defines the vector which will be filled with the Euler angles
  4614. * @param order is a reserved parameter and is ignore for now
  4615. * @returns the current unchanged quaternion
  4616. */
  4617. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4618. if (order === void 0) { order = "YZX"; }
  4619. var qz = this.z;
  4620. var qx = this.x;
  4621. var qy = this.y;
  4622. var qw = this.w;
  4623. var sqw = qw * qw;
  4624. var sqz = qz * qz;
  4625. var sqx = qx * qx;
  4626. var sqy = qy * qy;
  4627. var zAxisY = qy * qz - qx * qw;
  4628. var limit = .4999999;
  4629. if (zAxisY < -limit) {
  4630. result.y = 2 * Math.atan2(qy, qw);
  4631. result.x = Math.PI / 2;
  4632. result.z = 0;
  4633. }
  4634. else if (zAxisY > limit) {
  4635. result.y = 2 * Math.atan2(qy, qw);
  4636. result.x = -Math.PI / 2;
  4637. result.z = 0;
  4638. }
  4639. else {
  4640. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4641. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4642. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4643. }
  4644. return this;
  4645. };
  4646. /**
  4647. * Updates the given rotation matrix with the current quaternion values
  4648. * @param result defines the target matrix
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toRotationMatrix = function (result) {
  4652. var xx = this.x * this.x;
  4653. var yy = this.y * this.y;
  4654. var zz = this.z * this.z;
  4655. var xy = this.x * this.y;
  4656. var zw = this.z * this.w;
  4657. var zx = this.z * this.x;
  4658. var yw = this.y * this.w;
  4659. var yz = this.y * this.z;
  4660. var xw = this.x * this.w;
  4661. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4662. result.m[1] = 2.0 * (xy + zw);
  4663. result.m[2] = 2.0 * (zx - yw);
  4664. result.m[3] = 0;
  4665. result.m[4] = 2.0 * (xy - zw);
  4666. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4667. result.m[6] = 2.0 * (yz + xw);
  4668. result.m[7] = 0;
  4669. result.m[8] = 2.0 * (zx + yw);
  4670. result.m[9] = 2.0 * (yz - xw);
  4671. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4672. result.m[11] = 0;
  4673. result.m[12] = 0;
  4674. result.m[13] = 0;
  4675. result.m[14] = 0;
  4676. result.m[15] = 1.0;
  4677. result._markAsUpdated();
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion from the given rotation matrix values
  4682. * @param matrix defines the source matrix
  4683. * @returns the current updated quaternion
  4684. */
  4685. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4686. Quaternion.FromRotationMatrixToRef(matrix, this);
  4687. return this;
  4688. };
  4689. // Statics
  4690. /**
  4691. * Creates a new quaternion from a rotation matrix
  4692. * @param matrix defines the source matrix
  4693. * @returns a new quaternion created from the given rotation matrix values
  4694. */
  4695. Quaternion.FromRotationMatrix = function (matrix) {
  4696. var result = new Quaternion();
  4697. Quaternion.FromRotationMatrixToRef(matrix, result);
  4698. return result;
  4699. };
  4700. /**
  4701. * Updates the given quaternion with the given rotation matrix values
  4702. * @param matrix defines the source matrix
  4703. * @param result defines the target quaternion
  4704. */
  4705. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4706. var data = matrix.m;
  4707. var m11 = data[0], m12 = data[4], m13 = data[8];
  4708. var m21 = data[1], m22 = data[5], m23 = data[9];
  4709. var m31 = data[2], m32 = data[6], m33 = data[10];
  4710. var trace = m11 + m22 + m33;
  4711. var s;
  4712. if (trace > 0) {
  4713. s = 0.5 / Math.sqrt(trace + 1.0);
  4714. result.w = 0.25 / s;
  4715. result.x = (m32 - m23) * s;
  4716. result.y = (m13 - m31) * s;
  4717. result.z = (m21 - m12) * s;
  4718. }
  4719. else if (m11 > m22 && m11 > m33) {
  4720. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4721. result.w = (m32 - m23) / s;
  4722. result.x = 0.25 * s;
  4723. result.y = (m12 + m21) / s;
  4724. result.z = (m13 + m31) / s;
  4725. }
  4726. else if (m22 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4728. result.w = (m13 - m31) / s;
  4729. result.x = (m12 + m21) / s;
  4730. result.y = 0.25 * s;
  4731. result.z = (m23 + m32) / s;
  4732. }
  4733. else {
  4734. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4735. result.w = (m21 - m12) / s;
  4736. result.x = (m13 + m31) / s;
  4737. result.y = (m23 + m32) / s;
  4738. result.z = 0.25 * s;
  4739. }
  4740. };
  4741. /**
  4742. * Creates an empty quaternion
  4743. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4744. */
  4745. Quaternion.Zero = function () {
  4746. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4747. };
  4748. /**
  4749. * Inverse a given quaternion
  4750. * @param q defines the source quaternion
  4751. * @returns a new quaternion as the inverted current quaternion
  4752. */
  4753. Quaternion.Inverse = function (q) {
  4754. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4755. };
  4756. /**
  4757. * Creates an identity quaternion
  4758. * @returns the identity quaternion
  4759. */
  4760. Quaternion.Identity = function () {
  4761. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4762. };
  4763. /**
  4764. * Gets a boolean indicating if the given quaternion is identity
  4765. * @param quaternion defines the quaternion to check
  4766. * @returns true if the quaternion is identity
  4767. */
  4768. Quaternion.IsIdentity = function (quaternion) {
  4769. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4770. };
  4771. /**
  4772. * Creates a quaternion from a rotation around an axis
  4773. * @param axis defines the axis to use
  4774. * @param angle defines the angle to use
  4775. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4776. */
  4777. Quaternion.RotationAxis = function (axis, angle) {
  4778. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4779. };
  4780. /**
  4781. * Creates a rotation around an axis and stores it into the given quaternion
  4782. * @param axis defines the axis to use
  4783. * @param angle defines the angle to use
  4784. * @param result defines the target quaternion
  4785. * @returns the target quaternion
  4786. */
  4787. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4788. var sin = Math.sin(angle / 2);
  4789. axis.normalize();
  4790. result.w = Math.cos(angle / 2);
  4791. result.x = axis.x * sin;
  4792. result.y = axis.y * sin;
  4793. result.z = axis.z * sin;
  4794. return result;
  4795. };
  4796. /**
  4797. * Creates a new quaternion from data stored into an array
  4798. * @param array defines the data source
  4799. * @param offset defines the offset in the source array where the data starts
  4800. * @returns a new quaternion
  4801. */
  4802. Quaternion.FromArray = function (array, offset) {
  4803. if (!offset) {
  4804. offset = 0;
  4805. }
  4806. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4807. };
  4808. /**
  4809. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4810. * @param yaw defines the rotation around Y axis
  4811. * @param pitch defines the rotation around X axis
  4812. * @param roll defines the rotation around Z axis
  4813. * @returns the new quaternion
  4814. */
  4815. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4816. var q = new Quaternion();
  4817. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4818. return q;
  4819. };
  4820. /**
  4821. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4822. * @param yaw defines the rotation around Y axis
  4823. * @param pitch defines the rotation around X axis
  4824. * @param roll defines the rotation around Z axis
  4825. * @param result defines the target quaternion
  4826. */
  4827. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4828. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4829. var halfRoll = roll * 0.5;
  4830. var halfPitch = pitch * 0.5;
  4831. var halfYaw = yaw * 0.5;
  4832. var sinRoll = Math.sin(halfRoll);
  4833. var cosRoll = Math.cos(halfRoll);
  4834. var sinPitch = Math.sin(halfPitch);
  4835. var cosPitch = Math.cos(halfPitch);
  4836. var sinYaw = Math.sin(halfYaw);
  4837. var cosYaw = Math.cos(halfYaw);
  4838. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4839. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4840. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4841. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4842. };
  4843. /**
  4844. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4845. * @param alpha defines the rotation around first axis
  4846. * @param beta defines the rotation around second axis
  4847. * @param gamma defines the rotation around third axis
  4848. * @returns the new quaternion
  4849. */
  4850. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4851. var result = new Quaternion();
  4852. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4853. return result;
  4854. };
  4855. /**
  4856. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4857. * @param alpha defines the rotation around first axis
  4858. * @param beta defines the rotation around second axis
  4859. * @param gamma defines the rotation around third axis
  4860. * @param result defines the target quaternion
  4861. */
  4862. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4863. // Produces a quaternion from Euler angles in the z-x-z orientation
  4864. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4865. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4866. var halfBeta = beta * 0.5;
  4867. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4868. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4869. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4870. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4871. };
  4872. /**
  4873. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4874. * @param axis1 defines the first axis
  4875. * @param axis2 defines the second axis
  4876. * @param axis3 defines the third axis
  4877. * @returns the new quaternion
  4878. */
  4879. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4880. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4881. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4882. return quat;
  4883. };
  4884. /**
  4885. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4886. * @param axis1 defines the first axis
  4887. * @param axis2 defines the second axis
  4888. * @param axis3 defines the third axis
  4889. * @param ref defines the target quaternion
  4890. */
  4891. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4892. var rotMat = MathTmp.Matrix[0];
  4893. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4894. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4895. };
  4896. /**
  4897. * Interpolates between two quaternions
  4898. * @param left defines first quaternion
  4899. * @param right defines second quaternion
  4900. * @param amount defines the gradient to use
  4901. * @returns the new interpolated quaternion
  4902. */
  4903. Quaternion.Slerp = function (left, right, amount) {
  4904. var result = Quaternion.Identity();
  4905. Quaternion.SlerpToRef(left, right, amount, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Interpolates between two quaternions and stores it into a target quaternion
  4910. * @param left defines first quaternion
  4911. * @param right defines second quaternion
  4912. * @param amount defines the gradient to use
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4916. var num2;
  4917. var num3;
  4918. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4919. var flag = false;
  4920. if (num4 < 0) {
  4921. flag = true;
  4922. num4 = -num4;
  4923. }
  4924. if (num4 > 0.999999) {
  4925. num3 = 1 - amount;
  4926. num2 = flag ? -amount : amount;
  4927. }
  4928. else {
  4929. var num5 = Math.acos(num4);
  4930. var num6 = (1.0 / Math.sin(num5));
  4931. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4932. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4933. }
  4934. result.x = (num3 * left.x) + (num2 * right.x);
  4935. result.y = (num3 * left.y) + (num2 * right.y);
  4936. result.z = (num3 * left.z) + (num2 * right.z);
  4937. result.w = (num3 * left.w) + (num2 * right.w);
  4938. };
  4939. /**
  4940. * Interpolate between two quaternions using Hermite interpolation
  4941. * @param value1 defines first quaternion
  4942. * @param tangent1 defines the incoming tangent
  4943. * @param value2 defines second quaternion
  4944. * @param tangent2 defines the outgoing tangent
  4945. * @param amount defines the target quaternion
  4946. * @returns the new interpolated quaternion
  4947. */
  4948. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4949. var squared = amount * amount;
  4950. var cubed = amount * squared;
  4951. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4952. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4953. var part3 = (cubed - (2.0 * squared)) + amount;
  4954. var part4 = cubed - squared;
  4955. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4956. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4957. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4958. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4959. return new Quaternion(x, y, z, w);
  4960. };
  4961. return Quaternion;
  4962. }());
  4963. BABYLON.Quaternion = Quaternion;
  4964. /**
  4965. * Class used to store matrix data (4x4)
  4966. */
  4967. var Matrix = /** @class */ (function () {
  4968. /**
  4969. * Creates an empty matrix (filled with zeros)
  4970. */
  4971. function Matrix() {
  4972. this._isIdentity = false;
  4973. this._isIdentityDirty = true;
  4974. /**
  4975. * Gets or sets the internal data of the matrix
  4976. */
  4977. this.m = new Float32Array(16);
  4978. this._markAsUpdated();
  4979. }
  4980. /** @ignore */
  4981. Matrix.prototype._markAsUpdated = function () {
  4982. this.updateFlag = Matrix._updateFlagSeed++;
  4983. this._isIdentityDirty = true;
  4984. };
  4985. // Properties
  4986. /**
  4987. * Check if the current matrix is indentity
  4988. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4989. * @returns true is the matrix is the identity matrix
  4990. */
  4991. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4992. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4993. if (this._isIdentityDirty) {
  4994. this._isIdentityDirty = false;
  4995. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4996. this._isIdentity = false;
  4997. }
  4998. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4999. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5000. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5001. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5002. this._isIdentity = false;
  5003. }
  5004. else {
  5005. this._isIdentity = true;
  5006. }
  5007. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5008. this._isIdentity = false;
  5009. }
  5010. }
  5011. return this._isIdentity;
  5012. };
  5013. /**
  5014. * Gets the determinant of the matrix
  5015. * @returns the matrix determinant
  5016. */
  5017. Matrix.prototype.determinant = function () {
  5018. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5019. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5020. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5021. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5022. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5023. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5024. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5025. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5026. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5027. };
  5028. // Methods
  5029. /**
  5030. * Returns the matrix as a Float32Array
  5031. * @returns the matrix underlying array
  5032. */
  5033. Matrix.prototype.toArray = function () {
  5034. return this.m;
  5035. };
  5036. /**
  5037. * Returns the matrix as a Float32Array
  5038. * @returns the matrix underlying array.
  5039. */
  5040. Matrix.prototype.asArray = function () {
  5041. return this.toArray();
  5042. };
  5043. /**
  5044. * Inverts the current matrix in place
  5045. * @returns the current inverted matrix
  5046. */
  5047. Matrix.prototype.invert = function () {
  5048. this.invertToRef(this);
  5049. return this;
  5050. };
  5051. /**
  5052. * Sets all the matrix elements to zero
  5053. * @returns the current matrix
  5054. */
  5055. Matrix.prototype.reset = function () {
  5056. for (var index = 0; index < 16; index++) {
  5057. this.m[index] = 0.0;
  5058. }
  5059. this._markAsUpdated();
  5060. return this;
  5061. };
  5062. /**
  5063. * Adds the current matrix with a second one
  5064. * @param other defines the matrix to add
  5065. * @returns a new matrix as the addition of the current matrix and the given one
  5066. */
  5067. Matrix.prototype.add = function (other) {
  5068. var result = new Matrix();
  5069. this.addToRef(other, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5074. * @param other defines the matrix to add
  5075. * @param result defines the target matrix
  5076. * @returns the current matrix
  5077. */
  5078. Matrix.prototype.addToRef = function (other, result) {
  5079. for (var index = 0; index < 16; index++) {
  5080. result.m[index] = this.m[index] + other.m[index];
  5081. }
  5082. result._markAsUpdated();
  5083. return this;
  5084. };
  5085. /**
  5086. * Adds in place the given matrix to the current matrix
  5087. * @param other defines the second operand
  5088. * @returns the current updated matrix
  5089. */
  5090. Matrix.prototype.addToSelf = function (other) {
  5091. for (var index = 0; index < 16; index++) {
  5092. this.m[index] += other.m[index];
  5093. }
  5094. this._markAsUpdated();
  5095. return this;
  5096. };
  5097. /**
  5098. * Sets the given matrix to the current inverted Matrix
  5099. * @param other defines the target matrix
  5100. * @returns the unmodified current matrix
  5101. */
  5102. Matrix.prototype.invertToRef = function (other) {
  5103. var l1 = this.m[0];
  5104. var l2 = this.m[1];
  5105. var l3 = this.m[2];
  5106. var l4 = this.m[3];
  5107. var l5 = this.m[4];
  5108. var l6 = this.m[5];
  5109. var l7 = this.m[6];
  5110. var l8 = this.m[7];
  5111. var l9 = this.m[8];
  5112. var l10 = this.m[9];
  5113. var l11 = this.m[10];
  5114. var l12 = this.m[11];
  5115. var l13 = this.m[12];
  5116. var l14 = this.m[13];
  5117. var l15 = this.m[14];
  5118. var l16 = this.m[15];
  5119. var l17 = (l11 * l16) - (l12 * l15);
  5120. var l18 = (l10 * l16) - (l12 * l14);
  5121. var l19 = (l10 * l15) - (l11 * l14);
  5122. var l20 = (l9 * l16) - (l12 * l13);
  5123. var l21 = (l9 * l15) - (l11 * l13);
  5124. var l22 = (l9 * l14) - (l10 * l13);
  5125. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5126. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5127. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5128. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5129. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5130. var l28 = (l7 * l16) - (l8 * l15);
  5131. var l29 = (l6 * l16) - (l8 * l14);
  5132. var l30 = (l6 * l15) - (l7 * l14);
  5133. var l31 = (l5 * l16) - (l8 * l13);
  5134. var l32 = (l5 * l15) - (l7 * l13);
  5135. var l33 = (l5 * l14) - (l6 * l13);
  5136. var l34 = (l7 * l12) - (l8 * l11);
  5137. var l35 = (l6 * l12) - (l8 * l10);
  5138. var l36 = (l6 * l11) - (l7 * l10);
  5139. var l37 = (l5 * l12) - (l8 * l9);
  5140. var l38 = (l5 * l11) - (l7 * l9);
  5141. var l39 = (l5 * l10) - (l6 * l9);
  5142. other.m[0] = l23 * l27;
  5143. other.m[4] = l24 * l27;
  5144. other.m[8] = l25 * l27;
  5145. other.m[12] = l26 * l27;
  5146. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5147. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5148. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5149. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5150. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5151. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5152. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5153. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5154. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5155. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5156. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5157. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5158. other._markAsUpdated();
  5159. return this;
  5160. };
  5161. /**
  5162. * Inserts the translation vector (using 3 floats) in the current matrix
  5163. * @param x defines the 1st component of the translation
  5164. * @param y defines the 2nd component of the translation
  5165. * @param z defines the 3rd component of the translation
  5166. * @returns the current updated matrix
  5167. */
  5168. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5169. this.m[12] = x;
  5170. this.m[13] = y;
  5171. this.m[14] = z;
  5172. this._markAsUpdated();
  5173. return this;
  5174. };
  5175. /**
  5176. * Inserts the translation vector in the current matrix
  5177. * @param vector3 defines the translation to insert
  5178. * @returns the current updated matrix
  5179. */
  5180. Matrix.prototype.setTranslation = function (vector3) {
  5181. this.m[12] = vector3.x;
  5182. this.m[13] = vector3.y;
  5183. this.m[14] = vector3.z;
  5184. this._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Gets the translation value of the current matrix
  5189. * @returns a new Vector3 as the extracted translation from the matrix
  5190. */
  5191. Matrix.prototype.getTranslation = function () {
  5192. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5193. };
  5194. /**
  5195. * Fill a Vector3 with the extracted translation from the matrix
  5196. * @param result defines the Vector3 where to store the translation
  5197. * @returns the current matrix
  5198. */
  5199. Matrix.prototype.getTranslationToRef = function (result) {
  5200. result.x = this.m[12];
  5201. result.y = this.m[13];
  5202. result.z = this.m[14];
  5203. return this;
  5204. };
  5205. /**
  5206. * Remove rotation and scaling part from the matrix
  5207. * @returns the updated matrix
  5208. */
  5209. Matrix.prototype.removeRotationAndScaling = function () {
  5210. this.setRowFromFloats(0, 1, 0, 0, 0);
  5211. this.setRowFromFloats(1, 0, 1, 0, 0);
  5212. this.setRowFromFloats(2, 0, 0, 1, 0);
  5213. return this;
  5214. };
  5215. /**
  5216. * Multiply two matrices
  5217. * @param other defines the second operand
  5218. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5219. */
  5220. Matrix.prototype.multiply = function (other) {
  5221. var result = new Matrix();
  5222. this.multiplyToRef(other, result);
  5223. return result;
  5224. };
  5225. /**
  5226. * Copy the current matrix from the given one
  5227. * @param other defines the source matrix
  5228. * @returns the current updated matrix
  5229. */
  5230. Matrix.prototype.copyFrom = function (other) {
  5231. for (var index = 0; index < 16; index++) {
  5232. this.m[index] = other.m[index];
  5233. }
  5234. this._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Populates the given array from the starting index with the current matrix values
  5239. * @param array defines the target array
  5240. * @param offset defines the offset in the target array where to start storing values
  5241. * @returns the current matrix
  5242. */
  5243. Matrix.prototype.copyToArray = function (array, offset) {
  5244. if (offset === void 0) { offset = 0; }
  5245. for (var index = 0; index < 16; index++) {
  5246. array[offset + index] = this.m[index];
  5247. }
  5248. return this;
  5249. };
  5250. /**
  5251. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5252. * @param other defines the second operand
  5253. * @param result defines the matrix where to store the multiplication
  5254. * @returns the current matrix
  5255. */
  5256. Matrix.prototype.multiplyToRef = function (other, result) {
  5257. this.multiplyToArray(other, result.m, 0);
  5258. result._markAsUpdated();
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5263. * @param other defines the second operand
  5264. * @param result defines the array where to store the multiplication
  5265. * @param offset defines the offset in the target array where to start storing values
  5266. * @returns the current matrix
  5267. */
  5268. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5269. var tm0 = this.m[0];
  5270. var tm1 = this.m[1];
  5271. var tm2 = this.m[2];
  5272. var tm3 = this.m[3];
  5273. var tm4 = this.m[4];
  5274. var tm5 = this.m[5];
  5275. var tm6 = this.m[6];
  5276. var tm7 = this.m[7];
  5277. var tm8 = this.m[8];
  5278. var tm9 = this.m[9];
  5279. var tm10 = this.m[10];
  5280. var tm11 = this.m[11];
  5281. var tm12 = this.m[12];
  5282. var tm13 = this.m[13];
  5283. var tm14 = this.m[14];
  5284. var tm15 = this.m[15];
  5285. var om0 = other.m[0];
  5286. var om1 = other.m[1];
  5287. var om2 = other.m[2];
  5288. var om3 = other.m[3];
  5289. var om4 = other.m[4];
  5290. var om5 = other.m[5];
  5291. var om6 = other.m[6];
  5292. var om7 = other.m[7];
  5293. var om8 = other.m[8];
  5294. var om9 = other.m[9];
  5295. var om10 = other.m[10];
  5296. var om11 = other.m[11];
  5297. var om12 = other.m[12];
  5298. var om13 = other.m[13];
  5299. var om14 = other.m[14];
  5300. var om15 = other.m[15];
  5301. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5302. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5303. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5304. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5305. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5306. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5307. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5308. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5309. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5310. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5311. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5312. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5313. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5314. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5315. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5316. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5317. return this;
  5318. };
  5319. /**
  5320. * Check equality between this matrix and a second one
  5321. * @param value defines the second matrix to compare
  5322. * @returns true is the current matrix and the given one values are strictly equal
  5323. */
  5324. Matrix.prototype.equals = function (value) {
  5325. return value &&
  5326. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5327. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5328. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5329. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5330. };
  5331. /**
  5332. * Clone the current matrix
  5333. * @returns a new matrix from the current matrix
  5334. */
  5335. Matrix.prototype.clone = function () {
  5336. 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]);
  5337. };
  5338. /**
  5339. * Returns the name of the current matrix class
  5340. * @returns the string "Matrix"
  5341. */
  5342. Matrix.prototype.getClassName = function () {
  5343. return "Matrix";
  5344. };
  5345. /**
  5346. * Gets the hash code of the current matrix
  5347. * @returns the hash code
  5348. */
  5349. Matrix.prototype.getHashCode = function () {
  5350. var hash = this.m[0] || 0;
  5351. for (var i = 1; i < 16; i++) {
  5352. hash = (hash * 397) ^ (this.m[i] || 0);
  5353. }
  5354. return hash;
  5355. };
  5356. /**
  5357. * Decomposes the current Matrix into a translation, rotation and scaling components
  5358. * @param scale defines the scale vector3 given as a reference to update
  5359. * @param rotation defines the rotation quaternion given as a reference to update
  5360. * @param translation defines the translation vector3 given as a reference to update
  5361. * @returns true if operation was successful
  5362. */
  5363. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5364. if (translation) {
  5365. translation.x = this.m[12];
  5366. translation.y = this.m[13];
  5367. translation.z = this.m[14];
  5368. }
  5369. scale = scale || MathTmp.Vector3[0];
  5370. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5371. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5372. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5373. if (this.determinant() <= 0) {
  5374. scale.y *= -1;
  5375. }
  5376. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5377. if (rotation) {
  5378. rotation.x = 0;
  5379. rotation.y = 0;
  5380. rotation.z = 0;
  5381. rotation.w = 1;
  5382. }
  5383. return false;
  5384. }
  5385. if (rotation) {
  5386. 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]);
  5387. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5388. }
  5389. return true;
  5390. };
  5391. /**
  5392. * Gets specific row of the matrix
  5393. * @param index defines the number of the row to get
  5394. * @returns the index-th row of the current matrix as a new Vector4
  5395. */
  5396. Matrix.prototype.getRow = function (index) {
  5397. if (index < 0 || index > 3) {
  5398. return null;
  5399. }
  5400. var i = index * 4;
  5401. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5402. };
  5403. /**
  5404. * Sets the index-th row of the current matrix to the vector4 values
  5405. * @param index defines the number of the row to set
  5406. * @param row defines the target vector4
  5407. * @returns the updated current matrix
  5408. */
  5409. Matrix.prototype.setRow = function (index, row) {
  5410. if (index < 0 || index > 3) {
  5411. return this;
  5412. }
  5413. var i = index * 4;
  5414. this.m[i + 0] = row.x;
  5415. this.m[i + 1] = row.y;
  5416. this.m[i + 2] = row.z;
  5417. this.m[i + 3] = row.w;
  5418. this._markAsUpdated();
  5419. return this;
  5420. };
  5421. /**
  5422. * Compute the transpose of the matrix
  5423. * @returns the new transposed matrix
  5424. */
  5425. Matrix.prototype.transpose = function () {
  5426. return Matrix.Transpose(this);
  5427. };
  5428. /**
  5429. * Compute the transpose of the matrix and store it in a given matrix
  5430. * @param result defines the target matrix
  5431. * @returns the current matrix
  5432. */
  5433. Matrix.prototype.transposeToRef = function (result) {
  5434. Matrix.TransposeToRef(this, result);
  5435. return this;
  5436. };
  5437. /**
  5438. * Sets the index-th row of the current matrix with the given 4 x float values
  5439. * @param index defines the row index
  5440. * @param x defines the x component to set
  5441. * @param y defines the y component to set
  5442. * @param z defines the z component to set
  5443. * @param w defines the w component to set
  5444. * @returns the updated current matrix
  5445. */
  5446. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5447. if (index < 0 || index > 3) {
  5448. return this;
  5449. }
  5450. var i = index * 4;
  5451. this.m[i + 0] = x;
  5452. this.m[i + 1] = y;
  5453. this.m[i + 2] = z;
  5454. this.m[i + 3] = w;
  5455. this._markAsUpdated();
  5456. return this;
  5457. };
  5458. /**
  5459. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5460. * @param scale defines the scale factor
  5461. * @returns a new matrix
  5462. */
  5463. Matrix.prototype.scale = function (scale) {
  5464. var result = new Matrix();
  5465. this.scaleToRef(scale, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Scale the current matrix values by a factor to a given result matrix
  5470. * @param scale defines the scale factor
  5471. * @param result defines the matrix to store the result
  5472. * @returns the current matrix
  5473. */
  5474. Matrix.prototype.scaleToRef = function (scale, result) {
  5475. for (var index = 0; index < 16; index++) {
  5476. result.m[index] = this.m[index] * scale;
  5477. }
  5478. result._markAsUpdated();
  5479. return this;
  5480. };
  5481. /**
  5482. * Scale the current matrix values by a factor and add the result to a given matrix
  5483. * @param scale defines the scale factor
  5484. * @param result defines the Matrix to store the result
  5485. * @returns the current matrix
  5486. */
  5487. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5488. for (var index = 0; index < 16; index++) {
  5489. result.m[index] += this.m[index] * scale;
  5490. }
  5491. result._markAsUpdated();
  5492. return this;
  5493. };
  5494. /**
  5495. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5496. * @param ref matrix to store the result
  5497. */
  5498. Matrix.prototype.toNormalMatrix = function (ref) {
  5499. this.invertToRef(ref);
  5500. ref.transpose();
  5501. var m = ref.m;
  5502. 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);
  5503. };
  5504. /**
  5505. * Gets only rotation part of the current matrix
  5506. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5507. */
  5508. Matrix.prototype.getRotationMatrix = function () {
  5509. var result = Matrix.Identity();
  5510. this.getRotationMatrixToRef(result);
  5511. return result;
  5512. };
  5513. /**
  5514. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5515. * @param result defines the target matrix to store data to
  5516. * @returns the current matrix
  5517. */
  5518. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5519. var m = this.m;
  5520. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5521. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5522. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5523. if (this.determinant() <= 0) {
  5524. sy *= -1;
  5525. }
  5526. if (sx === 0 || sy === 0 || sz === 0) {
  5527. Matrix.IdentityToRef(result);
  5528. }
  5529. else {
  5530. 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);
  5531. }
  5532. return this;
  5533. };
  5534. // Statics
  5535. /**
  5536. * Creates a matrix from an array
  5537. * @param array defines the source array
  5538. * @param offset defines an offset in the source array
  5539. * @returns a new Matrix set from the starting index of the given array
  5540. */
  5541. Matrix.FromArray = function (array, offset) {
  5542. var result = new Matrix();
  5543. if (!offset) {
  5544. offset = 0;
  5545. }
  5546. Matrix.FromArrayToRef(array, offset, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Copy the content of an array into a given matrix
  5551. * @param array defines the source array
  5552. * @param offset defines an offset in the source array
  5553. * @param result defines the target matrix
  5554. */
  5555. Matrix.FromArrayToRef = function (array, offset, result) {
  5556. for (var index = 0; index < 16; index++) {
  5557. result.m[index] = array[index + offset];
  5558. }
  5559. result._markAsUpdated();
  5560. };
  5561. /**
  5562. * Stores an array into a matrix after having multiplied each component by a given factor
  5563. * @param array defines the source array
  5564. * @param offset defines the offset in the source array
  5565. * @param scale defines the scaling factor
  5566. * @param result defines the target matrix
  5567. */
  5568. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5569. for (var index = 0; index < 16; index++) {
  5570. result.m[index] = array[index + offset] * scale;
  5571. }
  5572. result._markAsUpdated();
  5573. };
  5574. /**
  5575. * Stores a list of values (16) inside a given matrix
  5576. * @param initialM11 defines 1st value of 1st row
  5577. * @param initialM12 defines 2nd value of 1st row
  5578. * @param initialM13 defines 3rd value of 1st row
  5579. * @param initialM14 defines 4th value of 1st row
  5580. * @param initialM21 defines 1st value of 2nd row
  5581. * @param initialM22 defines 2nd value of 2nd row
  5582. * @param initialM23 defines 3rd value of 2nd row
  5583. * @param initialM24 defines 4th value of 2nd row
  5584. * @param initialM31 defines 1st value of 3rd row
  5585. * @param initialM32 defines 2nd value of 3rd row
  5586. * @param initialM33 defines 3rd value of 3rd row
  5587. * @param initialM34 defines 4th value of 3rd row
  5588. * @param initialM41 defines 1st value of 4th row
  5589. * @param initialM42 defines 2nd value of 4th row
  5590. * @param initialM43 defines 3rd value of 4th row
  5591. * @param initialM44 defines 4th value of 4th row
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5595. result.m[0] = initialM11;
  5596. result.m[1] = initialM12;
  5597. result.m[2] = initialM13;
  5598. result.m[3] = initialM14;
  5599. result.m[4] = initialM21;
  5600. result.m[5] = initialM22;
  5601. result.m[6] = initialM23;
  5602. result.m[7] = initialM24;
  5603. result.m[8] = initialM31;
  5604. result.m[9] = initialM32;
  5605. result.m[10] = initialM33;
  5606. result.m[11] = initialM34;
  5607. result.m[12] = initialM41;
  5608. result.m[13] = initialM42;
  5609. result.m[14] = initialM43;
  5610. result.m[15] = initialM44;
  5611. result._markAsUpdated();
  5612. };
  5613. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5614. /**
  5615. * Gets an identity matrix that must not be updated
  5616. */
  5617. get: function () {
  5618. return Matrix._identityReadOnly;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. /**
  5624. * Creates new matrix from a list of values (16)
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @returns the new matrix
  5642. */
  5643. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5644. var result = new Matrix();
  5645. result.m[0] = initialM11;
  5646. result.m[1] = initialM12;
  5647. result.m[2] = initialM13;
  5648. result.m[3] = initialM14;
  5649. result.m[4] = initialM21;
  5650. result.m[5] = initialM22;
  5651. result.m[6] = initialM23;
  5652. result.m[7] = initialM24;
  5653. result.m[8] = initialM31;
  5654. result.m[9] = initialM32;
  5655. result.m[10] = initialM33;
  5656. result.m[11] = initialM34;
  5657. result.m[12] = initialM41;
  5658. result.m[13] = initialM42;
  5659. result.m[14] = initialM43;
  5660. result.m[15] = initialM44;
  5661. return result;
  5662. };
  5663. /**
  5664. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5665. * @param scale defines the scale vector3
  5666. * @param rotation defines the rotation quaternion
  5667. * @param translation defines the translation vector3
  5668. * @returns a new matrix
  5669. */
  5670. Matrix.Compose = function (scale, rotation, translation) {
  5671. var result = Matrix.Identity();
  5672. Matrix.ComposeToRef(scale, rotation, translation, result);
  5673. return result;
  5674. };
  5675. /**
  5676. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5677. * @param scale defines the scale vector3
  5678. * @param rotation defines the rotation quaternion
  5679. * @param translation defines the translation vector3
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5683. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5684. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5685. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5686. result.setTranslation(translation);
  5687. };
  5688. /**
  5689. * Creates a new identity matrix
  5690. * @returns a new identity matrix
  5691. */
  5692. Matrix.Identity = function () {
  5693. 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);
  5694. };
  5695. /**
  5696. * Creates a new identity matrix and stores the result in a given matrix
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.IdentityToRef = function (result) {
  5700. 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);
  5701. };
  5702. /**
  5703. * Creates a new zero matrix
  5704. * @returns a new zero matrix
  5705. */
  5706. Matrix.Zero = function () {
  5707. 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);
  5708. };
  5709. /**
  5710. * Creates a new rotation matrix for "angle" radians around the X axis
  5711. * @param angle defines the angle (in radians) to use
  5712. * @return the new matrix
  5713. */
  5714. Matrix.RotationX = function (angle) {
  5715. var result = new Matrix();
  5716. Matrix.RotationXToRef(angle, result);
  5717. return result;
  5718. };
  5719. /**
  5720. * Creates a new matrix as the invert of a given matrix
  5721. * @param source defines the source matrix
  5722. * @returns the new matrix
  5723. */
  5724. Matrix.Invert = function (source) {
  5725. var result = new Matrix();
  5726. source.invertToRef(result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5731. * @param angle defines the angle (in radians) to use
  5732. * @param result defines the target matrix
  5733. */
  5734. Matrix.RotationXToRef = function (angle, result) {
  5735. var s = Math.sin(angle);
  5736. var c = Math.cos(angle);
  5737. result.m[0] = 1.0;
  5738. result.m[15] = 1.0;
  5739. result.m[5] = c;
  5740. result.m[10] = c;
  5741. result.m[9] = -s;
  5742. result.m[6] = s;
  5743. result.m[1] = 0.0;
  5744. result.m[2] = 0.0;
  5745. result.m[3] = 0.0;
  5746. result.m[4] = 0.0;
  5747. result.m[7] = 0.0;
  5748. result.m[8] = 0.0;
  5749. result.m[11] = 0.0;
  5750. result.m[12] = 0.0;
  5751. result.m[13] = 0.0;
  5752. result.m[14] = 0.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the Y axis
  5757. * @param angle defines the angle (in radians) to use
  5758. * @return the new matrix
  5759. */
  5760. Matrix.RotationY = function (angle) {
  5761. var result = new Matrix();
  5762. Matrix.RotationYToRef(angle, result);
  5763. return result;
  5764. };
  5765. /**
  5766. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5767. * @param angle defines the angle (in radians) to use
  5768. * @param result defines the target matrix
  5769. */
  5770. Matrix.RotationYToRef = function (angle, result) {
  5771. var s = Math.sin(angle);
  5772. var c = Math.cos(angle);
  5773. result.m[5] = 1.0;
  5774. result.m[15] = 1.0;
  5775. result.m[0] = c;
  5776. result.m[2] = -s;
  5777. result.m[8] = s;
  5778. result.m[10] = c;
  5779. result.m[1] = 0.0;
  5780. result.m[3] = 0.0;
  5781. result.m[4] = 0.0;
  5782. result.m[6] = 0.0;
  5783. result.m[7] = 0.0;
  5784. result.m[9] = 0.0;
  5785. result.m[11] = 0.0;
  5786. result.m[12] = 0.0;
  5787. result.m[13] = 0.0;
  5788. result.m[14] = 0.0;
  5789. result._markAsUpdated();
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Z axis
  5793. * @param angle defines the angle (in radians) to use
  5794. * @return the new matrix
  5795. */
  5796. Matrix.RotationZ = function (angle) {
  5797. var result = new Matrix();
  5798. Matrix.RotationZToRef(angle, result);
  5799. return result;
  5800. };
  5801. /**
  5802. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5803. * @param angle defines the angle (in radians) to use
  5804. * @param result defines the target matrix
  5805. */
  5806. Matrix.RotationZToRef = function (angle, result) {
  5807. var s = Math.sin(angle);
  5808. var c = Math.cos(angle);
  5809. result.m[10] = 1.0;
  5810. result.m[15] = 1.0;
  5811. result.m[0] = c;
  5812. result.m[1] = s;
  5813. result.m[4] = -s;
  5814. result.m[5] = c;
  5815. result.m[2] = 0.0;
  5816. result.m[3] = 0.0;
  5817. result.m[6] = 0.0;
  5818. result.m[7] = 0.0;
  5819. result.m[8] = 0.0;
  5820. result.m[9] = 0.0;
  5821. result.m[11] = 0.0;
  5822. result.m[12] = 0.0;
  5823. result.m[13] = 0.0;
  5824. result.m[14] = 0.0;
  5825. result._markAsUpdated();
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the given axis
  5829. * @param axis defines the axis to use
  5830. * @param angle defines the angle (in radians) to use
  5831. * @return the new matrix
  5832. */
  5833. Matrix.RotationAxis = function (axis, angle) {
  5834. var result = Matrix.Zero();
  5835. Matrix.RotationAxisToRef(axis, angle, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5840. * @param axis defines the axis to use
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5845. var s = Math.sin(-angle);
  5846. var c = Math.cos(-angle);
  5847. var c1 = 1 - c;
  5848. axis.normalize();
  5849. result.m[0] = (axis.x * axis.x) * c1 + c;
  5850. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5851. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5852. result.m[3] = 0.0;
  5853. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5854. result.m[5] = (axis.y * axis.y) * c1 + c;
  5855. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5856. result.m[7] = 0.0;
  5857. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5858. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5859. result.m[10] = (axis.z * axis.z) * c1 + c;
  5860. result.m[11] = 0.0;
  5861. result.m[15] = 1.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a rotation matrix
  5866. * @param yaw defines the yaw angle in radians (Y axis)
  5867. * @param pitch defines the pitch angle in radians (X axis)
  5868. * @param roll defines the roll angle in radians (X axis)
  5869. * @returns the new rotation matrix
  5870. */
  5871. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5872. var result = new Matrix();
  5873. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a rotation matrix and stores it in a given matrix
  5878. * @param yaw defines the yaw angle in radians (Y axis)
  5879. * @param pitch defines the pitch angle in radians (X axis)
  5880. * @param roll defines the roll angle in radians (X axis)
  5881. * @param result defines the target matrix
  5882. */
  5883. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5885. this._tempQuaternion.toRotationMatrix(result);
  5886. };
  5887. /**
  5888. * Creates a scaling matrix
  5889. * @param x defines the scale factor on X axis
  5890. * @param y defines the scale factor on Y axis
  5891. * @param z defines the scale factor on Z axis
  5892. * @returns the new matrix
  5893. */
  5894. Matrix.Scaling = function (x, y, z) {
  5895. var result = Matrix.Zero();
  5896. Matrix.ScalingToRef(x, y, z, result);
  5897. return result;
  5898. };
  5899. /**
  5900. * Creates a scaling matrix and stores it in a given matrix
  5901. * @param x defines the scale factor on X axis
  5902. * @param y defines the scale factor on Y axis
  5903. * @param z defines the scale factor on Z axis
  5904. * @param result defines the target matrix
  5905. */
  5906. Matrix.ScalingToRef = function (x, y, z, result) {
  5907. result.m[0] = x;
  5908. result.m[1] = 0.0;
  5909. result.m[2] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[5] = y;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[8] = 0.0;
  5916. result.m[9] = 0.0;
  5917. result.m[10] = z;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result.m[15] = 1.0;
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Creates a translation matrix
  5927. * @param x defines the translation on X axis
  5928. * @param y defines the translation on Y axis
  5929. * @param z defines the translationon Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Translation = function (x, y, z) {
  5933. var result = Matrix.Identity();
  5934. Matrix.TranslationToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a translation matrix and stores it in a given matrix
  5939. * @param x defines the translation on X axis
  5940. * @param y defines the translation on Y axis
  5941. * @param z defines the translationon Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.TranslationToRef = function (x, y, z, result) {
  5945. 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);
  5946. };
  5947. /**
  5948. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5949. * @param startValue defines the start value
  5950. * @param endValue defines the end value
  5951. * @param gradient defines the gradient factor
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Lerp = function (startValue, endValue, gradient) {
  5955. var result = Matrix.Zero();
  5956. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5961. * @param startValue defines the start value
  5962. * @param endValue defines the end value
  5963. * @param gradient defines the gradient factor
  5964. * @param result defines the Matrix object where to store data
  5965. */
  5966. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5967. for (var index = 0; index < 16; index++) {
  5968. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5969. }
  5970. result._markAsUpdated();
  5971. };
  5972. /**
  5973. * Builds a new matrix whose values are computed by:
  5974. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5975. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5976. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5977. * @param startValue defines the first matrix
  5978. * @param endValue defines the second matrix
  5979. * @param gradient defines the gradient between the two matrices
  5980. * @returns the new matrix
  5981. */
  5982. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5983. var result = Matrix.Zero();
  5984. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Update a matrix to values which are computed by:
  5989. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5990. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5991. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5992. * @param startValue defines the first matrix
  5993. * @param endValue defines the second matrix
  5994. * @param gradient defines the gradient between the two matrices
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5998. var startScale = MathTmp.Vector3[0];
  5999. var startRotation = MathTmp.Quaternion[0];
  6000. var startTranslation = MathTmp.Vector3[1];
  6001. startValue.decompose(startScale, startRotation, startTranslation);
  6002. var endScale = MathTmp.Vector3[2];
  6003. var endRotation = MathTmp.Quaternion[1];
  6004. var endTranslation = MathTmp.Vector3[3];
  6005. endValue.decompose(endScale, endRotation, endTranslation);
  6006. var resultScale = MathTmp.Vector3[4];
  6007. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6008. var resultRotation = MathTmp.Quaternion[2];
  6009. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6010. var resultTranslation = MathTmp.Vector3[5];
  6011. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6012. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6013. };
  6014. /**
  6015. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6016. * This function works in left handed mode
  6017. * @param eye defines the final position of the entity
  6018. * @param target defines where the entity should look at
  6019. * @param up defines the up vector for the entity
  6020. * @returns the new matrix
  6021. */
  6022. Matrix.LookAtLH = function (eye, target, up) {
  6023. var result = Matrix.Zero();
  6024. Matrix.LookAtLHToRef(eye, target, up, result);
  6025. return result;
  6026. };
  6027. /**
  6028. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6029. * This function works in left handed mode
  6030. * @param eye defines the final position of the entity
  6031. * @param target defines where the entity should look at
  6032. * @param up defines the up vector for the entity
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6036. // Z axis
  6037. target.subtractToRef(eye, this._zAxis);
  6038. this._zAxis.normalize();
  6039. // X axis
  6040. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6041. if (this._xAxis.lengthSquared() === 0) {
  6042. this._xAxis.x = 1.0;
  6043. }
  6044. else {
  6045. this._xAxis.normalize();
  6046. }
  6047. // Y axis
  6048. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6049. this._yAxis.normalize();
  6050. // Eye angles
  6051. var ex = -Vector3.Dot(this._xAxis, eye);
  6052. var ey = -Vector3.Dot(this._yAxis, eye);
  6053. var ez = -Vector3.Dot(this._zAxis, eye);
  6054. 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);
  6055. };
  6056. /**
  6057. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6058. * This function works in right handed mode
  6059. * @param eye defines the final position of the entity
  6060. * @param target defines where the entity should look at
  6061. * @param up defines the up vector for the entity
  6062. * @returns the new matrix
  6063. */
  6064. Matrix.LookAtRH = function (eye, target, up) {
  6065. var result = Matrix.Zero();
  6066. Matrix.LookAtRHToRef(eye, target, up, result);
  6067. return result;
  6068. };
  6069. /**
  6070. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6071. * This function works in right handed mode
  6072. * @param eye defines the final position of the entity
  6073. * @param target defines where the entity should look at
  6074. * @param up defines the up vector for the entity
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6078. // Z axis
  6079. eye.subtractToRef(target, this._zAxis);
  6080. this._zAxis.normalize();
  6081. // X axis
  6082. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6083. if (this._xAxis.lengthSquared() === 0) {
  6084. this._xAxis.x = 1.0;
  6085. }
  6086. else {
  6087. this._xAxis.normalize();
  6088. }
  6089. // Y axis
  6090. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6091. this._yAxis.normalize();
  6092. // Eye angles
  6093. var ex = -Vector3.Dot(this._xAxis, eye);
  6094. var ey = -Vector3.Dot(this._yAxis, eye);
  6095. var ez = -Vector3.Dot(this._zAxis, eye);
  6096. 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);
  6097. };
  6098. /**
  6099. * Create a left-handed orthographic projection matrix
  6100. * @param width defines the viewport width
  6101. * @param height defines the viewport height
  6102. * @param znear defines the near clip plane
  6103. * @param zfar defines the far clip plane
  6104. * @returns a new matrix as a left-handed orthographic projection matrix
  6105. */
  6106. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6107. var matrix = Matrix.Zero();
  6108. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6109. return matrix;
  6110. };
  6111. /**
  6112. * Store a left-handed orthographic projection to a given matrix
  6113. * @param width defines the viewport width
  6114. * @param height defines the viewport height
  6115. * @param znear defines the near clip plane
  6116. * @param zfar defines the far clip plane
  6117. * @param result defines the target matrix
  6118. */
  6119. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6120. var n = znear;
  6121. var f = zfar;
  6122. var a = 2.0 / width;
  6123. var b = 2.0 / height;
  6124. var c = 2.0 / (f - n);
  6125. var d = -(f + n) / (f - n);
  6126. 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);
  6127. };
  6128. /**
  6129. * Create a left-handed orthographic projection matrix
  6130. * @param left defines the viewport left coordinate
  6131. * @param right defines the viewport right coordinate
  6132. * @param bottom defines the viewport bottom coordinate
  6133. * @param top defines the viewport top coordinate
  6134. * @param znear defines the near clip plane
  6135. * @param zfar defines the far clip plane
  6136. * @returns a new matrix as a left-handed orthographic projection matrix
  6137. */
  6138. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6139. var matrix = Matrix.Zero();
  6140. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6141. return matrix;
  6142. };
  6143. /**
  6144. * Stores a left-handed orthographic projection into a given matrix
  6145. * @param left defines the viewport left coordinate
  6146. * @param right defines the viewport right coordinate
  6147. * @param bottom defines the viewport bottom coordinate
  6148. * @param top defines the viewport top coordinate
  6149. * @param znear defines the near clip plane
  6150. * @param zfar defines the far clip plane
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6154. var n = znear;
  6155. var f = zfar;
  6156. var a = 2.0 / (right - left);
  6157. var b = 2.0 / (top - bottom);
  6158. var c = 2.0 / (f - n);
  6159. var d = -(f + n) / (f - n);
  6160. var i0 = (left + right) / (left - right);
  6161. var i1 = (top + bottom) / (bottom - top);
  6162. 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);
  6163. };
  6164. /**
  6165. * Creates a right-handed orthographic projection matrix
  6166. * @param left defines the viewport left coordinate
  6167. * @param right defines the viewport right coordinate
  6168. * @param bottom defines the viewport bottom coordinate
  6169. * @param top defines the viewport top coordinate
  6170. * @param znear defines the near clip plane
  6171. * @param zfar defines the far clip plane
  6172. * @returns a new matrix as a right-handed orthographic projection matrix
  6173. */
  6174. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6175. var matrix = Matrix.Zero();
  6176. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6177. return matrix;
  6178. };
  6179. /**
  6180. * Stores a right-handed orthographic projection into a given matrix
  6181. * @param left defines the viewport left coordinate
  6182. * @param right defines the viewport right coordinate
  6183. * @param bottom defines the viewport bottom coordinate
  6184. * @param top defines the viewport top coordinate
  6185. * @param znear defines the near clip plane
  6186. * @param zfar defines the far clip plane
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6190. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6191. result.m[10] *= -1.0;
  6192. };
  6193. /**
  6194. * Creates a left-handed perspective projection matrix
  6195. * @param width defines the viewport width
  6196. * @param height defines the viewport height
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a left-handed perspective projection matrix
  6200. */
  6201. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 * n / width;
  6206. var b = 2.0 * n / height;
  6207. var c = (f + n) / (f - n);
  6208. var d = -2.0 * f * n / (f - n);
  6209. 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);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Creates a left-handed perspective projection matrix
  6214. * @param fov defines the horizontal field of view
  6215. * @param aspect defines the aspect ratio
  6216. * @param znear defines the near clip plane
  6217. * @param zfar defines the far clip plane
  6218. * @returns a new matrix as a left-handed perspective projection matrix
  6219. */
  6220. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6221. var matrix = Matrix.Zero();
  6222. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6223. return matrix;
  6224. };
  6225. /**
  6226. * Stores a left-handed perspective projection into a given matrix
  6227. * @param fov defines the horizontal field of view
  6228. * @param aspect defines the aspect ratio
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @param result defines the target matrix
  6232. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6233. */
  6234. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6235. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6236. var n = znear;
  6237. var f = zfar;
  6238. var t = 1.0 / (Math.tan(fov * 0.5));
  6239. var a = isVerticalFovFixed ? (t / aspect) : t;
  6240. var b = isVerticalFovFixed ? t : (t * aspect);
  6241. var c = (f + n) / (f - n);
  6242. var d = -2.0 * f * n / (f - n);
  6243. 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);
  6244. };
  6245. /**
  6246. * Creates a right-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a right-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a right-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. //alternatively this could be expressed as:
  6269. // m = PerspectiveFovLHToRef
  6270. // m[10] *= -1.0;
  6271. // m[11] *= -1.0;
  6272. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6273. var n = znear;
  6274. var f = zfar;
  6275. var t = 1.0 / (Math.tan(fov * 0.5));
  6276. var a = isVerticalFovFixed ? (t / aspect) : t;
  6277. var b = isVerticalFovFixed ? t : (t * aspect);
  6278. var c = -(f + n) / (f - n);
  6279. var d = -2 * f * n / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Stores a perspective projection for WebVR info a given matrix
  6284. * @param fov defines the field of view
  6285. * @param znear defines the near clip plane
  6286. * @param zfar defines the far clip plane
  6287. * @param result defines the target matrix
  6288. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6289. */
  6290. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6291. if (rightHanded === void 0) { rightHanded = false; }
  6292. var rightHandedFactor = rightHanded ? -1 : 1;
  6293. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6294. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6295. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6296. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6297. var xScale = 2.0 / (leftTan + rightTan);
  6298. var yScale = 2.0 / (upTan + downTan);
  6299. result.m[0] = xScale;
  6300. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6301. result.m[5] = yScale;
  6302. result.m[6] = result.m[7] = 0.0;
  6303. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6304. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6305. result.m[10] = -zfar / (znear - zfar);
  6306. result.m[11] = 1.0 * rightHandedFactor;
  6307. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6308. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6309. result._markAsUpdated();
  6310. };
  6311. /**
  6312. * Computes a complete transformation matrix
  6313. * @param viewport defines the viewport to use
  6314. * @param world defines the world matrix
  6315. * @param view defines the view matrix
  6316. * @param projection defines the projection matrix
  6317. * @param zmin defines the near clip plane
  6318. * @param zmax defines the far clip plane
  6319. * @returns the transformation matrix
  6320. */
  6321. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6322. var cw = viewport.width;
  6323. var ch = viewport.height;
  6324. var cx = viewport.x;
  6325. var cy = viewport.y;
  6326. 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);
  6327. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6328. };
  6329. /**
  6330. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6331. * @param matrix defines the matrix to use
  6332. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6333. */
  6334. Matrix.GetAsMatrix2x2 = function (matrix) {
  6335. return new Float32Array([
  6336. matrix.m[0], matrix.m[1],
  6337. matrix.m[4], matrix.m[5]
  6338. ]);
  6339. };
  6340. /**
  6341. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6342. * @param matrix defines the matrix to use
  6343. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6344. */
  6345. Matrix.GetAsMatrix3x3 = function (matrix) {
  6346. return new Float32Array([
  6347. matrix.m[0], matrix.m[1], matrix.m[2],
  6348. matrix.m[4], matrix.m[5], matrix.m[6],
  6349. matrix.m[8], matrix.m[9], matrix.m[10]
  6350. ]);
  6351. };
  6352. /**
  6353. * Compute the transpose of a given matrix
  6354. * @param matrix defines the matrix to transpose
  6355. * @returns the new matrix
  6356. */
  6357. Matrix.Transpose = function (matrix) {
  6358. var result = new Matrix();
  6359. Matrix.TransposeToRef(matrix, result);
  6360. return result;
  6361. };
  6362. /**
  6363. * Compute the transpose of a matrix and store it in a target matrix
  6364. * @param matrix defines the matrix to transpose
  6365. * @param result defines the target matrix
  6366. */
  6367. Matrix.TransposeToRef = function (matrix, result) {
  6368. result.m[0] = matrix.m[0];
  6369. result.m[1] = matrix.m[4];
  6370. result.m[2] = matrix.m[8];
  6371. result.m[3] = matrix.m[12];
  6372. result.m[4] = matrix.m[1];
  6373. result.m[5] = matrix.m[5];
  6374. result.m[6] = matrix.m[9];
  6375. result.m[7] = matrix.m[13];
  6376. result.m[8] = matrix.m[2];
  6377. result.m[9] = matrix.m[6];
  6378. result.m[10] = matrix.m[10];
  6379. result.m[11] = matrix.m[14];
  6380. result.m[12] = matrix.m[3];
  6381. result.m[13] = matrix.m[7];
  6382. result.m[14] = matrix.m[11];
  6383. result.m[15] = matrix.m[15];
  6384. };
  6385. /**
  6386. * Computes a reflection matrix from a plane
  6387. * @param plane defines the reflection plane
  6388. * @returns a new matrix
  6389. */
  6390. Matrix.Reflection = function (plane) {
  6391. var matrix = new Matrix();
  6392. Matrix.ReflectionToRef(plane, matrix);
  6393. return matrix;
  6394. };
  6395. /**
  6396. * Computes a reflection matrix from a plane
  6397. * @param plane defines the reflection plane
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.ReflectionToRef = function (plane, result) {
  6401. plane.normalize();
  6402. var x = plane.normal.x;
  6403. var y = plane.normal.y;
  6404. var z = plane.normal.z;
  6405. var temp = -2 * x;
  6406. var temp2 = -2 * y;
  6407. var temp3 = -2 * z;
  6408. result.m[0] = (temp * x) + 1;
  6409. result.m[1] = temp2 * x;
  6410. result.m[2] = temp3 * x;
  6411. result.m[3] = 0.0;
  6412. result.m[4] = temp * y;
  6413. result.m[5] = (temp2 * y) + 1;
  6414. result.m[6] = temp3 * y;
  6415. result.m[7] = 0.0;
  6416. result.m[8] = temp * z;
  6417. result.m[9] = temp2 * z;
  6418. result.m[10] = (temp3 * z) + 1;
  6419. result.m[11] = 0.0;
  6420. result.m[12] = temp * plane.d;
  6421. result.m[13] = temp2 * plane.d;
  6422. result.m[14] = temp3 * plane.d;
  6423. result.m[15] = 1.0;
  6424. result._markAsUpdated();
  6425. };
  6426. /**
  6427. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6428. * @param xaxis defines the value of the 1st axis
  6429. * @param yaxis defines the value of the 2nd axis
  6430. * @param zaxis defines the value of the 3rd axis
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6434. result.m[0] = xaxis.x;
  6435. result.m[1] = xaxis.y;
  6436. result.m[2] = xaxis.z;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = yaxis.x;
  6439. result.m[5] = yaxis.y;
  6440. result.m[6] = yaxis.z;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = zaxis.x;
  6443. result.m[9] = zaxis.y;
  6444. result.m[10] = zaxis.z;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = 0.0;
  6447. result.m[13] = 0.0;
  6448. result.m[14] = 0.0;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6454. * @param quat defines the quaternion to use
  6455. * @param result defines the target matrix
  6456. */
  6457. Matrix.FromQuaternionToRef = function (quat, result) {
  6458. var xx = quat.x * quat.x;
  6459. var yy = quat.y * quat.y;
  6460. var zz = quat.z * quat.z;
  6461. var xy = quat.x * quat.y;
  6462. var zw = quat.z * quat.w;
  6463. var zx = quat.z * quat.x;
  6464. var yw = quat.y * quat.w;
  6465. var yz = quat.y * quat.z;
  6466. var xw = quat.x * quat.w;
  6467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6468. result.m[1] = 2.0 * (xy + zw);
  6469. result.m[2] = 2.0 * (zx - yw);
  6470. result.m[3] = 0.0;
  6471. result.m[4] = 2.0 * (xy - zw);
  6472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6473. result.m[6] = 2.0 * (yz + xw);
  6474. result.m[7] = 0.0;
  6475. result.m[8] = 2.0 * (zx + yw);
  6476. result.m[9] = 2.0 * (yz - xw);
  6477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. Matrix._tempQuaternion = new Quaternion();
  6486. Matrix._xAxis = Vector3.Zero();
  6487. Matrix._yAxis = Vector3.Zero();
  6488. Matrix._zAxis = Vector3.Zero();
  6489. Matrix._updateFlagSeed = 0;
  6490. Matrix._identityReadOnly = Matrix.Identity();
  6491. return Matrix;
  6492. }());
  6493. BABYLON.Matrix = Matrix;
  6494. var Plane = /** @class */ (function () {
  6495. /**
  6496. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6497. */
  6498. function Plane(a, b, c, d) {
  6499. this.normal = new Vector3(a, b, c);
  6500. this.d = d;
  6501. }
  6502. /**
  6503. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6504. */
  6505. Plane.prototype.asArray = function () {
  6506. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6507. };
  6508. // Methods
  6509. /**
  6510. * Returns a new plane copied from the current Plane.
  6511. */
  6512. Plane.prototype.clone = function () {
  6513. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6514. };
  6515. /**
  6516. * Returns the string "Plane".
  6517. */
  6518. Plane.prototype.getClassName = function () {
  6519. return "Plane";
  6520. };
  6521. /**
  6522. * Returns the Plane hash code.
  6523. */
  6524. Plane.prototype.getHashCode = function () {
  6525. var hash = this.normal.getHashCode();
  6526. hash = (hash * 397) ^ (this.d || 0);
  6527. return hash;
  6528. };
  6529. /**
  6530. * Normalize the current Plane in place.
  6531. * Returns the updated Plane.
  6532. */
  6533. Plane.prototype.normalize = function () {
  6534. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6535. var magnitude = 0.0;
  6536. if (norm !== 0) {
  6537. magnitude = 1.0 / norm;
  6538. }
  6539. this.normal.x *= magnitude;
  6540. this.normal.y *= magnitude;
  6541. this.normal.z *= magnitude;
  6542. this.d *= magnitude;
  6543. return this;
  6544. };
  6545. /**
  6546. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6547. */
  6548. Plane.prototype.transform = function (transformation) {
  6549. var transposedMatrix = Matrix.Transpose(transformation);
  6550. var x = this.normal.x;
  6551. var y = this.normal.y;
  6552. var z = this.normal.z;
  6553. var d = this.d;
  6554. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6555. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6556. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6557. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6558. return new Plane(normalX, normalY, normalZ, finalD);
  6559. };
  6560. /**
  6561. * Returns the dot product (float) of the point coordinates and the plane normal.
  6562. */
  6563. Plane.prototype.dotCoordinate = function (point) {
  6564. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6565. };
  6566. /**
  6567. * Updates the current Plane from the plane defined by the three given points.
  6568. * Returns the updated Plane.
  6569. */
  6570. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6571. var x1 = point2.x - point1.x;
  6572. var y1 = point2.y - point1.y;
  6573. var z1 = point2.z - point1.z;
  6574. var x2 = point3.x - point1.x;
  6575. var y2 = point3.y - point1.y;
  6576. var z2 = point3.z - point1.z;
  6577. var yz = (y1 * z2) - (z1 * y2);
  6578. var xz = (z1 * x2) - (x1 * z2);
  6579. var xy = (x1 * y2) - (y1 * x2);
  6580. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6581. var invPyth;
  6582. if (pyth !== 0) {
  6583. invPyth = 1.0 / pyth;
  6584. }
  6585. else {
  6586. invPyth = 0.0;
  6587. }
  6588. this.normal.x = yz * invPyth;
  6589. this.normal.y = xz * invPyth;
  6590. this.normal.z = xy * invPyth;
  6591. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6592. return this;
  6593. };
  6594. /**
  6595. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6596. */
  6597. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6598. var dot = Vector3.Dot(this.normal, direction);
  6599. return (dot <= epsilon);
  6600. };
  6601. /**
  6602. * Returns the signed distance (float) from the given point to the Plane.
  6603. */
  6604. Plane.prototype.signedDistanceTo = function (point) {
  6605. return Vector3.Dot(point, this.normal) + this.d;
  6606. };
  6607. // Statics
  6608. /**
  6609. * Returns a new Plane from the given array.
  6610. */
  6611. Plane.FromArray = function (array) {
  6612. return new Plane(array[0], array[1], array[2], array[3]);
  6613. };
  6614. /**
  6615. * Returns a new Plane defined by the three given points.
  6616. */
  6617. Plane.FromPoints = function (point1, point2, point3) {
  6618. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6619. result.copyFromPoints(point1, point2, point3);
  6620. return result;
  6621. };
  6622. /**
  6623. * Returns a new Plane the normal vector to this plane at the given origin point.
  6624. * Note : the vector "normal" is updated because normalized.
  6625. */
  6626. Plane.FromPositionAndNormal = function (origin, normal) {
  6627. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6628. normal.normalize();
  6629. result.normal = normal;
  6630. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6631. return result;
  6632. };
  6633. /**
  6634. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6635. */
  6636. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6637. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6638. return Vector3.Dot(point, normal) + d;
  6639. };
  6640. return Plane;
  6641. }());
  6642. BABYLON.Plane = Plane;
  6643. var Viewport = /** @class */ (function () {
  6644. /**
  6645. * Creates a Viewport object located at (x, y) and sized (width, height).
  6646. */
  6647. function Viewport(x, y, width, height) {
  6648. this.x = x;
  6649. this.y = y;
  6650. this.width = width;
  6651. this.height = height;
  6652. }
  6653. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6654. if (renderWidthOrEngine.getRenderWidth) {
  6655. var engine = renderWidthOrEngine;
  6656. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6657. }
  6658. var renderWidth = renderWidthOrEngine;
  6659. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6660. };
  6661. /**
  6662. * Returns a new Viewport copied from the current one.
  6663. */
  6664. Viewport.prototype.clone = function () {
  6665. return new Viewport(this.x, this.y, this.width, this.height);
  6666. };
  6667. return Viewport;
  6668. }());
  6669. BABYLON.Viewport = Viewport;
  6670. var Frustum = /** @class */ (function () {
  6671. function Frustum() {
  6672. }
  6673. /**
  6674. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6675. */
  6676. Frustum.GetPlanes = function (transform) {
  6677. var frustumPlanes = [];
  6678. for (var index = 0; index < 6; index++) {
  6679. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6680. }
  6681. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6682. return frustumPlanes;
  6683. };
  6684. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6685. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6686. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6687. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6688. frustumPlane.d = transform.m[15] + transform.m[14];
  6689. frustumPlane.normalize();
  6690. };
  6691. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6692. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6693. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6694. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6695. frustumPlane.d = transform.m[15] - transform.m[14];
  6696. frustumPlane.normalize();
  6697. };
  6698. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6699. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6700. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6701. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6702. frustumPlane.d = transform.m[15] + transform.m[12];
  6703. frustumPlane.normalize();
  6704. };
  6705. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6706. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6707. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6708. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6709. frustumPlane.d = transform.m[15] - transform.m[12];
  6710. frustumPlane.normalize();
  6711. };
  6712. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6713. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6714. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6715. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6716. frustumPlane.d = transform.m[15] - transform.m[13];
  6717. frustumPlane.normalize();
  6718. };
  6719. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6720. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6721. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6722. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6723. frustumPlane.d = transform.m[15] + transform.m[13];
  6724. frustumPlane.normalize();
  6725. };
  6726. /**
  6727. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6730. // Near
  6731. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6732. // Far
  6733. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6734. // Left
  6735. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6736. // Right
  6737. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6738. // Top
  6739. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6740. // Bottom
  6741. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6742. };
  6743. return Frustum;
  6744. }());
  6745. BABYLON.Frustum = Frustum;
  6746. var Space;
  6747. (function (Space) {
  6748. Space[Space["LOCAL"] = 0] = "LOCAL";
  6749. Space[Space["WORLD"] = 1] = "WORLD";
  6750. Space[Space["BONE"] = 2] = "BONE";
  6751. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6752. var Axis = /** @class */ (function () {
  6753. function Axis() {
  6754. }
  6755. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6756. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6757. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6758. return Axis;
  6759. }());
  6760. BABYLON.Axis = Axis;
  6761. ;
  6762. var BezierCurve = /** @class */ (function () {
  6763. function BezierCurve() {
  6764. }
  6765. /**
  6766. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6767. */
  6768. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6769. // Extract X (which is equal to time here)
  6770. var f0 = 1 - 3 * x2 + 3 * x1;
  6771. var f1 = 3 * x2 - 6 * x1;
  6772. var f2 = 3 * x1;
  6773. var refinedT = t;
  6774. for (var i = 0; i < 5; i++) {
  6775. var refinedT2 = refinedT * refinedT;
  6776. var refinedT3 = refinedT2 * refinedT;
  6777. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6778. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6779. refinedT -= (x - t) * slope;
  6780. refinedT = Math.min(1, Math.max(0, refinedT));
  6781. }
  6782. // Resolve cubic bezier for the given x
  6783. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6784. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6785. Math.pow(refinedT, 3);
  6786. };
  6787. return BezierCurve;
  6788. }());
  6789. BABYLON.BezierCurve = BezierCurve;
  6790. var Orientation;
  6791. (function (Orientation) {
  6792. Orientation[Orientation["CW"] = 0] = "CW";
  6793. Orientation[Orientation["CCW"] = 1] = "CCW";
  6794. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6795. var Angle = /** @class */ (function () {
  6796. /**
  6797. * Creates an Angle object of "radians" radians (float).
  6798. */
  6799. function Angle(radians) {
  6800. var _this = this;
  6801. /**
  6802. * Returns the Angle value in degrees (float).
  6803. */
  6804. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6805. /**
  6806. * Returns the Angle value in radians (float).
  6807. */
  6808. this.radians = function () { return _this._radians; };
  6809. this._radians = radians;
  6810. if (this._radians < 0.0)
  6811. this._radians += (2.0 * Math.PI);
  6812. }
  6813. /**
  6814. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6815. */
  6816. Angle.BetweenTwoPoints = function (a, b) {
  6817. var delta = b.subtract(a);
  6818. var theta = Math.atan2(delta.y, delta.x);
  6819. return new Angle(theta);
  6820. };
  6821. /**
  6822. * Returns a new Angle object from the given float in radians.
  6823. */
  6824. Angle.FromRadians = function (radians) {
  6825. return new Angle(radians);
  6826. };
  6827. /**
  6828. * Returns a new Angle object from the given float in degrees.
  6829. */
  6830. Angle.FromDegrees = function (degrees) {
  6831. return new Angle(degrees * Math.PI / 180.0);
  6832. };
  6833. return Angle;
  6834. }());
  6835. BABYLON.Angle = Angle;
  6836. var Arc2 = /** @class */ (function () {
  6837. /**
  6838. * Creates an Arc object from the three given points : start, middle and end.
  6839. */
  6840. function Arc2(startPoint, midPoint, endPoint) {
  6841. this.startPoint = startPoint;
  6842. this.midPoint = midPoint;
  6843. this.endPoint = endPoint;
  6844. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6845. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6846. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6847. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6848. 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);
  6849. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6850. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6851. var a1 = this.startAngle.degrees();
  6852. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6853. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6854. // angles correction
  6855. if (a2 - a1 > +180.0)
  6856. a2 -= 360.0;
  6857. if (a2 - a1 < -180.0)
  6858. a2 += 360.0;
  6859. if (a3 - a2 > +180.0)
  6860. a3 -= 360.0;
  6861. if (a3 - a2 < -180.0)
  6862. a3 += 360.0;
  6863. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6864. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6865. }
  6866. return Arc2;
  6867. }());
  6868. BABYLON.Arc2 = Arc2;
  6869. var Path2 = /** @class */ (function () {
  6870. /**
  6871. * Creates a Path2 object from the starting 2D coordinates x and y.
  6872. */
  6873. function Path2(x, y) {
  6874. this._points = new Array();
  6875. this._length = 0.0;
  6876. this.closed = false;
  6877. this._points.push(new Vector2(x, y));
  6878. }
  6879. /**
  6880. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6881. * Returns the updated Path2.
  6882. */
  6883. Path2.prototype.addLineTo = function (x, y) {
  6884. if (this.closed) {
  6885. return this;
  6886. }
  6887. var newPoint = new Vector2(x, y);
  6888. var previousPoint = this._points[this._points.length - 1];
  6889. this._points.push(newPoint);
  6890. this._length += newPoint.subtract(previousPoint).length();
  6891. return this;
  6892. };
  6893. /**
  6894. * 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.
  6895. * Returns the updated Path2.
  6896. */
  6897. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6898. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6899. if (this.closed) {
  6900. return this;
  6901. }
  6902. var startPoint = this._points[this._points.length - 1];
  6903. var midPoint = new Vector2(midX, midY);
  6904. var endPoint = new Vector2(endX, endY);
  6905. var arc = new Arc2(startPoint, midPoint, endPoint);
  6906. var increment = arc.angle.radians() / numberOfSegments;
  6907. if (arc.orientation === Orientation.CW)
  6908. increment *= -1;
  6909. var currentAngle = arc.startAngle.radians() + increment;
  6910. for (var i = 0; i < numberOfSegments; i++) {
  6911. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6912. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6913. this.addLineTo(x, y);
  6914. currentAngle += increment;
  6915. }
  6916. return this;
  6917. };
  6918. /**
  6919. * Closes the Path2.
  6920. * Returns the Path2.
  6921. */
  6922. Path2.prototype.close = function () {
  6923. this.closed = true;
  6924. return this;
  6925. };
  6926. /**
  6927. * Returns the Path2 total length (float).
  6928. */
  6929. Path2.prototype.length = function () {
  6930. var result = this._length;
  6931. if (!this.closed) {
  6932. var lastPoint = this._points[this._points.length - 1];
  6933. var firstPoint = this._points[0];
  6934. result += (firstPoint.subtract(lastPoint).length());
  6935. }
  6936. return result;
  6937. };
  6938. /**
  6939. * Returns the Path2 internal array of points.
  6940. */
  6941. Path2.prototype.getPoints = function () {
  6942. return this._points;
  6943. };
  6944. /**
  6945. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6946. */
  6947. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6948. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6949. return Vector2.Zero();
  6950. }
  6951. var lengthPosition = normalizedLengthPosition * this.length();
  6952. var previousOffset = 0;
  6953. for (var i = 0; i < this._points.length; i++) {
  6954. var j = (i + 1) % this._points.length;
  6955. var a = this._points[i];
  6956. var b = this._points[j];
  6957. var bToA = b.subtract(a);
  6958. var nextOffset = (bToA.length() + previousOffset);
  6959. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6960. var dir = bToA.normalize();
  6961. var localOffset = lengthPosition - previousOffset;
  6962. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6963. }
  6964. previousOffset = nextOffset;
  6965. }
  6966. return Vector2.Zero();
  6967. };
  6968. /**
  6969. * Returns a new Path2 starting at the coordinates (x, y).
  6970. */
  6971. Path2.StartingAt = function (x, y) {
  6972. return new Path2(x, y);
  6973. };
  6974. return Path2;
  6975. }());
  6976. BABYLON.Path2 = Path2;
  6977. var Path3D = /** @class */ (function () {
  6978. /**
  6979. * new Path3D(path, normal, raw)
  6980. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6981. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6982. * path : an array of Vector3, the curve axis of the Path3D
  6983. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6984. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6985. */
  6986. function Path3D(path, firstNormal, raw) {
  6987. if (firstNormal === void 0) { firstNormal = null; }
  6988. this.path = path;
  6989. this._curve = new Array();
  6990. this._distances = new Array();
  6991. this._tangents = new Array();
  6992. this._normals = new Array();
  6993. this._binormals = new Array();
  6994. for (var p = 0; p < path.length; p++) {
  6995. this._curve[p] = path[p].clone(); // hard copy
  6996. }
  6997. this._raw = raw || false;
  6998. this._compute(firstNormal);
  6999. }
  7000. /**
  7001. * Returns the Path3D array of successive Vector3 designing its curve.
  7002. */
  7003. Path3D.prototype.getCurve = function () {
  7004. return this._curve;
  7005. };
  7006. /**
  7007. * Returns an array populated with tangent vectors on each Path3D curve point.
  7008. */
  7009. Path3D.prototype.getTangents = function () {
  7010. return this._tangents;
  7011. };
  7012. /**
  7013. * Returns an array populated with normal vectors on each Path3D curve point.
  7014. */
  7015. Path3D.prototype.getNormals = function () {
  7016. return this._normals;
  7017. };
  7018. /**
  7019. * Returns an array populated with binormal vectors on each Path3D curve point.
  7020. */
  7021. Path3D.prototype.getBinormals = function () {
  7022. return this._binormals;
  7023. };
  7024. /**
  7025. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7026. */
  7027. Path3D.prototype.getDistances = function () {
  7028. return this._distances;
  7029. };
  7030. /**
  7031. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7032. * Returns the same object updated.
  7033. */
  7034. Path3D.prototype.update = function (path, firstNormal) {
  7035. if (firstNormal === void 0) { firstNormal = null; }
  7036. for (var p = 0; p < path.length; p++) {
  7037. this._curve[p].x = path[p].x;
  7038. this._curve[p].y = path[p].y;
  7039. this._curve[p].z = path[p].z;
  7040. }
  7041. this._compute(firstNormal);
  7042. return this;
  7043. };
  7044. // private function compute() : computes tangents, normals and binormals
  7045. Path3D.prototype._compute = function (firstNormal) {
  7046. var l = this._curve.length;
  7047. // first and last tangents
  7048. this._tangents[0] = this._getFirstNonNullVector(0);
  7049. if (!this._raw) {
  7050. this._tangents[0].normalize();
  7051. }
  7052. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7053. if (!this._raw) {
  7054. this._tangents[l - 1].normalize();
  7055. }
  7056. // normals and binormals at first point : arbitrary vector with _normalVector()
  7057. var tg0 = this._tangents[0];
  7058. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7059. this._normals[0] = pp0;
  7060. if (!this._raw) {
  7061. this._normals[0].normalize();
  7062. }
  7063. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7064. if (!this._raw) {
  7065. this._binormals[0].normalize();
  7066. }
  7067. this._distances[0] = 0.0;
  7068. // normals and binormals : next points
  7069. var prev; // previous vector (segment)
  7070. var cur; // current vector (segment)
  7071. var curTang; // current tangent
  7072. // previous normal
  7073. var prevBinor; // previous binormal
  7074. for (var i = 1; i < l; i++) {
  7075. // tangents
  7076. prev = this._getLastNonNullVector(i);
  7077. if (i < l - 1) {
  7078. cur = this._getFirstNonNullVector(i);
  7079. this._tangents[i] = prev.add(cur);
  7080. this._tangents[i].normalize();
  7081. }
  7082. this._distances[i] = this._distances[i - 1] + prev.length();
  7083. // normals and binormals
  7084. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7085. curTang = this._tangents[i];
  7086. prevBinor = this._binormals[i - 1];
  7087. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7088. if (!this._raw) {
  7089. this._normals[i].normalize();
  7090. }
  7091. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7092. if (!this._raw) {
  7093. this._binormals[i].normalize();
  7094. }
  7095. }
  7096. };
  7097. // private function getFirstNonNullVector(index)
  7098. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7099. Path3D.prototype._getFirstNonNullVector = function (index) {
  7100. var i = 1;
  7101. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7102. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7103. i++;
  7104. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7105. }
  7106. return nNVector;
  7107. };
  7108. // private function getLastNonNullVector(index)
  7109. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7110. Path3D.prototype._getLastNonNullVector = function (index) {
  7111. var i = 1;
  7112. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7113. while (nLVector.length() === 0 && index > i + 1) {
  7114. i++;
  7115. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7116. }
  7117. return nLVector;
  7118. };
  7119. // private function normalVector(v0, vt, va) :
  7120. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7121. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7122. Path3D.prototype._normalVector = function (v0, vt, va) {
  7123. var normal0;
  7124. var tgl = vt.length();
  7125. if (tgl === 0.0) {
  7126. tgl = 1.0;
  7127. }
  7128. if (va === undefined || va === null) {
  7129. var point;
  7130. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7131. point = new Vector3(0.0, -1.0, 0.0);
  7132. }
  7133. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7134. point = new Vector3(1.0, 0.0, 0.0);
  7135. }
  7136. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7137. point = new Vector3(0.0, 0.0, 1.0);
  7138. }
  7139. else {
  7140. point = Vector3.Zero();
  7141. }
  7142. normal0 = Vector3.Cross(vt, point);
  7143. }
  7144. else {
  7145. normal0 = Vector3.Cross(vt, va);
  7146. Vector3.CrossToRef(normal0, vt, normal0);
  7147. }
  7148. normal0.normalize();
  7149. return normal0;
  7150. };
  7151. return Path3D;
  7152. }());
  7153. BABYLON.Path3D = Path3D;
  7154. var Curve3 = /** @class */ (function () {
  7155. /**
  7156. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7157. * A Curve3 is designed from a series of successive Vector3.
  7158. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7159. */
  7160. function Curve3(points) {
  7161. this._length = 0.0;
  7162. this._points = points;
  7163. this._length = this._computeLength(points);
  7164. }
  7165. /**
  7166. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7167. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7168. * @param v1 (Vector3) the control point
  7169. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7170. * @param nbPoints (integer) the wanted number of points in the curve
  7171. */
  7172. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7173. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7174. var bez = new Array();
  7175. var equation = function (t, val0, val1, val2) {
  7176. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7177. return res;
  7178. };
  7179. for (var i = 0; i <= nbPoints; i++) {
  7180. 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)));
  7181. }
  7182. return new Curve3(bez);
  7183. };
  7184. /**
  7185. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7186. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7187. * @param v1 (Vector3) the first control point
  7188. * @param v2 (Vector3) the second control point
  7189. * @param v3 (Vector3) the end point of the Cubic Bezier
  7190. * @param nbPoints (integer) the wanted number of points in the curve
  7191. */
  7192. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7193. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7194. var bez = new Array();
  7195. var equation = function (t, val0, val1, val2, val3) {
  7196. 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;
  7197. return res;
  7198. };
  7199. for (var i = 0; i <= nbPoints; i++) {
  7200. 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)));
  7201. }
  7202. return new Curve3(bez);
  7203. };
  7204. /**
  7205. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7206. * @param p1 (Vector3) the origin point of the Hermite Spline
  7207. * @param t1 (Vector3) the tangent vector at the origin point
  7208. * @param p2 (Vector3) the end point of the Hermite Spline
  7209. * @param t2 (Vector3) the tangent vector at the end point
  7210. * @param nbPoints (integer) the wanted number of points in the curve
  7211. */
  7212. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7213. var hermite = new Array();
  7214. var step = 1.0 / nbPoints;
  7215. for (var i = 0; i <= nbPoints; i++) {
  7216. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7217. }
  7218. return new Curve3(hermite);
  7219. };
  7220. /**
  7221. * Returns a Curve3 object along a CatmullRom Spline curve :
  7222. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7223. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7224. */
  7225. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7226. var totalPoints = new Array();
  7227. totalPoints.push(points[0].clone());
  7228. Array.prototype.push.apply(totalPoints, points);
  7229. totalPoints.push(points[points.length - 1].clone());
  7230. var catmullRom = new Array();
  7231. var step = 1.0 / nbPoints;
  7232. var amount = 0.0;
  7233. for (var i = 0; i < totalPoints.length - 3; i++) {
  7234. amount = 0;
  7235. for (var c = 0; c < nbPoints; c++) {
  7236. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7237. amount += step;
  7238. }
  7239. }
  7240. i--;
  7241. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7242. return new Curve3(catmullRom);
  7243. };
  7244. /**
  7245. * Returns the Curve3 stored array of successive Vector3
  7246. */
  7247. Curve3.prototype.getPoints = function () {
  7248. return this._points;
  7249. };
  7250. /**
  7251. * Returns the computed length (float) of the curve.
  7252. */
  7253. Curve3.prototype.length = function () {
  7254. return this._length;
  7255. };
  7256. /**
  7257. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7258. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7259. * curveA and curveB keep unchanged.
  7260. */
  7261. Curve3.prototype.continue = function (curve) {
  7262. var lastPoint = this._points[this._points.length - 1];
  7263. var continuedPoints = this._points.slice();
  7264. var curvePoints = curve.getPoints();
  7265. for (var i = 1; i < curvePoints.length; i++) {
  7266. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7267. }
  7268. var continuedCurve = new Curve3(continuedPoints);
  7269. return continuedCurve;
  7270. };
  7271. Curve3.prototype._computeLength = function (path) {
  7272. var l = 0;
  7273. for (var i = 1; i < path.length; i++) {
  7274. l += (path[i].subtract(path[i - 1])).length();
  7275. }
  7276. return l;
  7277. };
  7278. return Curve3;
  7279. }());
  7280. BABYLON.Curve3 = Curve3;
  7281. // Vertex formats
  7282. var PositionNormalVertex = /** @class */ (function () {
  7283. function PositionNormalVertex(position, normal) {
  7284. if (position === void 0) { position = Vector3.Zero(); }
  7285. if (normal === void 0) { normal = Vector3.Up(); }
  7286. this.position = position;
  7287. this.normal = normal;
  7288. }
  7289. PositionNormalVertex.prototype.clone = function () {
  7290. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7291. };
  7292. return PositionNormalVertex;
  7293. }());
  7294. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7295. var PositionNormalTextureVertex = /** @class */ (function () {
  7296. function PositionNormalTextureVertex(position, normal, uv) {
  7297. if (position === void 0) { position = Vector3.Zero(); }
  7298. if (normal === void 0) { normal = Vector3.Up(); }
  7299. if (uv === void 0) { uv = Vector2.Zero(); }
  7300. this.position = position;
  7301. this.normal = normal;
  7302. this.uv = uv;
  7303. }
  7304. PositionNormalTextureVertex.prototype.clone = function () {
  7305. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7306. };
  7307. return PositionNormalTextureVertex;
  7308. }());
  7309. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7310. // Temporary pre-allocated objects for engine internal use
  7311. // usage in any internal function :
  7312. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7313. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7314. var Tmp = /** @class */ (function () {
  7315. function Tmp() {
  7316. }
  7317. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7318. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7319. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7320. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7321. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7322. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7323. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7324. Matrix.Zero(), Matrix.Zero(),
  7325. Matrix.Zero(), Matrix.Zero(),
  7326. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7327. return Tmp;
  7328. }());
  7329. BABYLON.Tmp = Tmp;
  7330. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7331. var MathTmp = /** @class */ (function () {
  7332. function MathTmp() {
  7333. }
  7334. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7335. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7336. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7337. return MathTmp;
  7338. }());
  7339. })(BABYLON || (BABYLON = {}));
  7340. //# sourceMappingURL=babylon.math.js.map
  7341. var BABYLON;
  7342. (function (BABYLON) {
  7343. var Scalar = /** @class */ (function () {
  7344. function Scalar() {
  7345. }
  7346. /**
  7347. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7348. */
  7349. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7350. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7351. var num = a - b;
  7352. return -epsilon <= num && num <= epsilon;
  7353. };
  7354. /**
  7355. * Returns a string : the upper case translation of the number i to hexadecimal.
  7356. */
  7357. Scalar.ToHex = function (i) {
  7358. var str = i.toString(16);
  7359. if (i <= 15) {
  7360. return ("0" + str).toUpperCase();
  7361. }
  7362. return str.toUpperCase();
  7363. };
  7364. /**
  7365. * Returns -1 if value is negative and +1 is value is positive.
  7366. * Returns the value itself if it's equal to zero.
  7367. */
  7368. Scalar.Sign = function (value) {
  7369. value = +value; // convert to a number
  7370. if (value === 0 || isNaN(value))
  7371. return value;
  7372. return value > 0 ? 1 : -1;
  7373. };
  7374. /**
  7375. * Returns the value itself if it's between min and max.
  7376. * Returns min if the value is lower than min.
  7377. * Returns max if the value is greater than max.
  7378. */
  7379. Scalar.Clamp = function (value, min, max) {
  7380. if (min === void 0) { min = 0; }
  7381. if (max === void 0) { max = 1; }
  7382. return Math.min(max, Math.max(min, value));
  7383. };
  7384. /**
  7385. * Returns the log2 of value.
  7386. */
  7387. Scalar.Log2 = function (value) {
  7388. return Math.log(value) * Math.LOG2E;
  7389. };
  7390. /**
  7391. * Loops the value, so that it is never larger than length and never smaller than 0.
  7392. *
  7393. * This is similar to the modulo operator but it works with floating point numbers.
  7394. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7395. * With t = 5 and length = 2.5, the result would be 0.0.
  7396. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7397. */
  7398. Scalar.Repeat = function (value, length) {
  7399. return value - Math.floor(value / length) * length;
  7400. };
  7401. /**
  7402. * Normalize the value between 0.0 and 1.0 using min and max values
  7403. */
  7404. Scalar.Normalize = function (value, min, max) {
  7405. return (value - min) / (max - min);
  7406. };
  7407. /**
  7408. * Denormalize the value from 0.0 and 1.0 using min and max values
  7409. */
  7410. Scalar.Denormalize = function (normalized, min, max) {
  7411. return (normalized * (max - min) + min);
  7412. };
  7413. /**
  7414. * Calculates the shortest difference between two given angles given in degrees.
  7415. */
  7416. Scalar.DeltaAngle = function (current, target) {
  7417. var num = Scalar.Repeat(target - current, 360.0);
  7418. if (num > 180.0) {
  7419. num -= 360.0;
  7420. }
  7421. return num;
  7422. };
  7423. /**
  7424. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7425. *
  7426. * The returned value will move back and forth between 0 and length
  7427. */
  7428. Scalar.PingPong = function (tx, length) {
  7429. var t = Scalar.Repeat(tx, length * 2.0);
  7430. return length - Math.abs(t - length);
  7431. };
  7432. /**
  7433. * Interpolates between min and max with smoothing at the limits.
  7434. *
  7435. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7436. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7437. */
  7438. Scalar.SmoothStep = function (from, to, tx) {
  7439. var t = Scalar.Clamp(tx);
  7440. t = -2.0 * t * t * t + 3.0 * t * t;
  7441. return to * t + from * (1.0 - t);
  7442. };
  7443. /**
  7444. * Moves a value current towards target.
  7445. *
  7446. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7447. * Negative values of maxDelta pushes the value away from target.
  7448. */
  7449. Scalar.MoveTowards = function (current, target, maxDelta) {
  7450. var result = 0;
  7451. if (Math.abs(target - current) <= maxDelta) {
  7452. result = target;
  7453. }
  7454. else {
  7455. result = current + Scalar.Sign(target - current) * maxDelta;
  7456. }
  7457. return result;
  7458. };
  7459. /**
  7460. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7461. *
  7462. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7463. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7464. */
  7465. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7466. var num = Scalar.DeltaAngle(current, target);
  7467. var result = 0;
  7468. if (-maxDelta < num && num < maxDelta) {
  7469. result = target;
  7470. }
  7471. else {
  7472. target = current + num;
  7473. result = Scalar.MoveTowards(current, target, maxDelta);
  7474. }
  7475. return result;
  7476. };
  7477. /**
  7478. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7479. */
  7480. Scalar.Lerp = function (start, end, amount) {
  7481. return start + ((end - start) * amount);
  7482. };
  7483. /**
  7484. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7485. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7486. */
  7487. Scalar.LerpAngle = function (start, end, amount) {
  7488. var num = Scalar.Repeat(end - start, 360.0);
  7489. if (num > 180.0) {
  7490. num -= 360.0;
  7491. }
  7492. return start + num * Scalar.Clamp(amount);
  7493. };
  7494. /**
  7495. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7496. */
  7497. Scalar.InverseLerp = function (a, b, value) {
  7498. var result = 0;
  7499. if (a != b) {
  7500. result = Scalar.Clamp((value - a) / (b - a));
  7501. }
  7502. else {
  7503. result = 0.0;
  7504. }
  7505. return result;
  7506. };
  7507. /**
  7508. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7509. */
  7510. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7511. var squared = amount * amount;
  7512. var cubed = amount * squared;
  7513. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7514. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7515. var part3 = (cubed - (2.0 * squared)) + amount;
  7516. var part4 = cubed - squared;
  7517. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7518. };
  7519. /**
  7520. * Returns a random float number between and min and max values
  7521. */
  7522. Scalar.RandomRange = function (min, max) {
  7523. if (min === max)
  7524. return min;
  7525. return ((Math.random() * (max - min)) + min);
  7526. };
  7527. /**
  7528. * This function returns percentage of a number in a given range.
  7529. *
  7530. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7531. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7532. */
  7533. Scalar.RangeToPercent = function (number, min, max) {
  7534. return ((number - min) / (max - min));
  7535. };
  7536. /**
  7537. * This function returns number that corresponds to the percentage in a given range.
  7538. *
  7539. * PercentToRange(0.34,0,100) will return 34.
  7540. */
  7541. Scalar.PercentToRange = function (percent, min, max) {
  7542. return ((max - min) * percent + min);
  7543. };
  7544. /**
  7545. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7546. * @param angle The angle to normalize in radian.
  7547. * @return The converted angle.
  7548. */
  7549. Scalar.NormalizeRadians = function (angle) {
  7550. // More precise but slower version kept for reference.
  7551. // angle = angle % Tools.TwoPi;
  7552. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7553. //if (angle > Math.PI) {
  7554. // angle -= Tools.TwoPi;
  7555. //}
  7556. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7557. return angle;
  7558. };
  7559. /**
  7560. * Two pi constants convenient for computation.
  7561. */
  7562. Scalar.TwoPi = Math.PI * 2;
  7563. return Scalar;
  7564. }());
  7565. BABYLON.Scalar = Scalar;
  7566. })(BABYLON || (BABYLON = {}));
  7567. //# sourceMappingURL=babylon.math.scalar.js.map
  7568. //# sourceMappingURL=babylon.mixins.js.map
  7569. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7570. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7571. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7572. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7573. //# sourceMappingURL=babylon.webgl2.js.map
  7574. var BABYLON;
  7575. (function (BABYLON) {
  7576. var __decoratorInitialStore = {};
  7577. var __mergedStore = {};
  7578. var _copySource = function (creationFunction, source, instanciate) {
  7579. var destination = creationFunction();
  7580. // Tags
  7581. if (BABYLON.Tags) {
  7582. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7583. }
  7584. var classStore = getMergedStore(destination);
  7585. // Properties
  7586. for (var property in classStore) {
  7587. var propertyDescriptor = classStore[property];
  7588. var sourceProperty = source[property];
  7589. var propertyType = propertyDescriptor.type;
  7590. if (sourceProperty !== undefined && sourceProperty !== null) {
  7591. switch (propertyType) {
  7592. case 0: // Value
  7593. case 6: // Mesh reference
  7594. case 11: // Camera reference
  7595. destination[property] = sourceProperty;
  7596. break;
  7597. case 1: // Texture
  7598. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7599. break;
  7600. case 2: // Color3
  7601. case 3: // FresnelParameters
  7602. case 4: // Vector2
  7603. case 5: // Vector3
  7604. case 7: // Color Curves
  7605. case 10: // Quaternion
  7606. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7607. break;
  7608. }
  7609. }
  7610. }
  7611. return destination;
  7612. };
  7613. function getDirectStore(target) {
  7614. var classKey = target.getClassName();
  7615. if (!__decoratorInitialStore[classKey]) {
  7616. __decoratorInitialStore[classKey] = {};
  7617. }
  7618. return __decoratorInitialStore[classKey];
  7619. }
  7620. /**
  7621. * Return the list of properties flagged as serializable
  7622. * @param target: host object
  7623. */
  7624. function getMergedStore(target) {
  7625. var classKey = target.getClassName();
  7626. if (__mergedStore[classKey]) {
  7627. return __mergedStore[classKey];
  7628. }
  7629. __mergedStore[classKey] = {};
  7630. var store = __mergedStore[classKey];
  7631. var currentTarget = target;
  7632. var currentKey = classKey;
  7633. while (currentKey) {
  7634. var initialStore = __decoratorInitialStore[currentKey];
  7635. for (var property in initialStore) {
  7636. store[property] = initialStore[property];
  7637. }
  7638. var parent_1 = void 0;
  7639. var done = false;
  7640. do {
  7641. parent_1 = Object.getPrototypeOf(currentTarget);
  7642. if (!parent_1.getClassName) {
  7643. done = true;
  7644. break;
  7645. }
  7646. if (parent_1.getClassName() !== currentKey) {
  7647. break;
  7648. }
  7649. currentTarget = parent_1;
  7650. } while (parent_1);
  7651. if (done) {
  7652. break;
  7653. }
  7654. currentKey = parent_1.getClassName();
  7655. currentTarget = parent_1;
  7656. }
  7657. return store;
  7658. }
  7659. function generateSerializableMember(type, sourceName) {
  7660. return function (target, propertyKey) {
  7661. var classStore = getDirectStore(target);
  7662. if (!classStore[propertyKey]) {
  7663. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7664. }
  7665. };
  7666. }
  7667. function generateExpandMember(setCallback, targetKey) {
  7668. if (targetKey === void 0) { targetKey = null; }
  7669. return function (target, propertyKey) {
  7670. var key = targetKey || ("_" + propertyKey);
  7671. Object.defineProperty(target, propertyKey, {
  7672. get: function () {
  7673. return this[key];
  7674. },
  7675. set: function (value) {
  7676. if (this[key] === value) {
  7677. return;
  7678. }
  7679. this[key] = value;
  7680. target[setCallback].apply(this);
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. };
  7686. }
  7687. function expandToProperty(callback, targetKey) {
  7688. if (targetKey === void 0) { targetKey = null; }
  7689. return generateExpandMember(callback, targetKey);
  7690. }
  7691. BABYLON.expandToProperty = expandToProperty;
  7692. function serialize(sourceName) {
  7693. return generateSerializableMember(0, sourceName); // value member
  7694. }
  7695. BABYLON.serialize = serialize;
  7696. function serializeAsTexture(sourceName) {
  7697. return generateSerializableMember(1, sourceName); // texture member
  7698. }
  7699. BABYLON.serializeAsTexture = serializeAsTexture;
  7700. function serializeAsColor3(sourceName) {
  7701. return generateSerializableMember(2, sourceName); // color3 member
  7702. }
  7703. BABYLON.serializeAsColor3 = serializeAsColor3;
  7704. function serializeAsFresnelParameters(sourceName) {
  7705. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7706. }
  7707. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7708. function serializeAsVector2(sourceName) {
  7709. return generateSerializableMember(4, sourceName); // vector2 member
  7710. }
  7711. BABYLON.serializeAsVector2 = serializeAsVector2;
  7712. function serializeAsVector3(sourceName) {
  7713. return generateSerializableMember(5, sourceName); // vector3 member
  7714. }
  7715. BABYLON.serializeAsVector3 = serializeAsVector3;
  7716. function serializeAsMeshReference(sourceName) {
  7717. return generateSerializableMember(6, sourceName); // mesh reference member
  7718. }
  7719. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7720. function serializeAsColorCurves(sourceName) {
  7721. return generateSerializableMember(7, sourceName); // color curves
  7722. }
  7723. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7724. function serializeAsColor4(sourceName) {
  7725. return generateSerializableMember(8, sourceName); // color 4
  7726. }
  7727. BABYLON.serializeAsColor4 = serializeAsColor4;
  7728. function serializeAsImageProcessingConfiguration(sourceName) {
  7729. return generateSerializableMember(9, sourceName); // image processing
  7730. }
  7731. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7732. function serializeAsQuaternion(sourceName) {
  7733. return generateSerializableMember(10, sourceName); // quaternion member
  7734. }
  7735. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7736. /**
  7737. * Decorator used to define property that can be serialized as reference to a camera
  7738. * @param sourceName defines the name of the property to decorate
  7739. */
  7740. function serializeAsCameraReference(sourceName) {
  7741. return generateSerializableMember(11, sourceName); // camera reference member
  7742. }
  7743. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7744. var SerializationHelper = /** @class */ (function () {
  7745. function SerializationHelper() {
  7746. }
  7747. SerializationHelper.Serialize = function (entity, serializationObject) {
  7748. if (!serializationObject) {
  7749. serializationObject = {};
  7750. }
  7751. // Tags
  7752. if (BABYLON.Tags) {
  7753. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7754. }
  7755. var serializedProperties = getMergedStore(entity);
  7756. // Properties
  7757. for (var property in serializedProperties) {
  7758. var propertyDescriptor = serializedProperties[property];
  7759. var targetPropertyName = propertyDescriptor.sourceName || property;
  7760. var propertyType = propertyDescriptor.type;
  7761. var sourceProperty = entity[property];
  7762. if (sourceProperty !== undefined && sourceProperty !== null) {
  7763. switch (propertyType) {
  7764. case 0: // Value
  7765. serializationObject[targetPropertyName] = sourceProperty;
  7766. break;
  7767. case 1: // Texture
  7768. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7769. break;
  7770. case 2: // Color3
  7771. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7772. break;
  7773. case 3: // FresnelParameters
  7774. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7775. break;
  7776. case 4: // Vector2
  7777. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7778. break;
  7779. case 5: // Vector3
  7780. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7781. break;
  7782. case 6: // Mesh reference
  7783. serializationObject[targetPropertyName] = sourceProperty.id;
  7784. break;
  7785. case 7: // Color Curves
  7786. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7787. break;
  7788. case 8: // Color 4
  7789. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7790. break;
  7791. case 9: // Image Processing
  7792. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7793. break;
  7794. case 10: // Quaternion
  7795. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7796. break;
  7797. case 11: // Camera reference
  7798. serializationObject[targetPropertyName] = sourceProperty.id;
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. return serializationObject;
  7804. };
  7805. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7806. if (rootUrl === void 0) { rootUrl = null; }
  7807. var destination = creationFunction();
  7808. if (!rootUrl) {
  7809. rootUrl = "";
  7810. }
  7811. // Tags
  7812. if (BABYLON.Tags) {
  7813. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7814. }
  7815. var classStore = getMergedStore(destination);
  7816. // Properties
  7817. for (var property in classStore) {
  7818. var propertyDescriptor = classStore[property];
  7819. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7820. var propertyType = propertyDescriptor.type;
  7821. if (sourceProperty !== undefined && sourceProperty !== null) {
  7822. var dest = destination;
  7823. switch (propertyType) {
  7824. case 0: // Value
  7825. dest[property] = sourceProperty;
  7826. break;
  7827. case 1: // Texture
  7828. if (scene) {
  7829. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7830. }
  7831. break;
  7832. case 2: // Color3
  7833. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7834. break;
  7835. case 3: // FresnelParameters
  7836. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7837. break;
  7838. case 4: // Vector2
  7839. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7840. break;
  7841. case 5: // Vector3
  7842. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7843. break;
  7844. case 6: // Mesh reference
  7845. if (scene) {
  7846. dest[property] = scene.getLastMeshByID(sourceProperty);
  7847. }
  7848. break;
  7849. case 7: // Color Curves
  7850. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7851. break;
  7852. case 8: // Color 4
  7853. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7854. break;
  7855. case 9: // Image Processing
  7856. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7857. break;
  7858. case 10: // Quaternion
  7859. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7860. break;
  7861. case 11: // Camera reference
  7862. if (scene) {
  7863. dest[property] = scene.getCameraByID(sourceProperty);
  7864. }
  7865. break;
  7866. }
  7867. }
  7868. }
  7869. return destination;
  7870. };
  7871. SerializationHelper.Clone = function (creationFunction, source) {
  7872. return _copySource(creationFunction, source, false);
  7873. };
  7874. SerializationHelper.Instanciate = function (creationFunction, source) {
  7875. return _copySource(creationFunction, source, true);
  7876. };
  7877. return SerializationHelper;
  7878. }());
  7879. BABYLON.SerializationHelper = SerializationHelper;
  7880. })(BABYLON || (BABYLON = {}));
  7881. //# sourceMappingURL=babylon.decorators.js.map
  7882. var BABYLON;
  7883. (function (BABYLON) {
  7884. /**
  7885. * Wrapper class for promise with external resolve and reject.
  7886. */
  7887. var Deferred = /** @class */ (function () {
  7888. /**
  7889. * Constructor for this deferred object.
  7890. */
  7891. function Deferred() {
  7892. var _this = this;
  7893. this.promise = new Promise(function (resolve, reject) {
  7894. _this._resolve = resolve;
  7895. _this._reject = reject;
  7896. });
  7897. }
  7898. Object.defineProperty(Deferred.prototype, "resolve", {
  7899. /**
  7900. * The resolve method of the promise associated with this deferred object.
  7901. */
  7902. get: function () {
  7903. return this._resolve;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Deferred.prototype, "reject", {
  7909. /**
  7910. * The reject method of the promise associated with this deferred object.
  7911. */
  7912. get: function () {
  7913. return this._reject;
  7914. },
  7915. enumerable: true,
  7916. configurable: true
  7917. });
  7918. return Deferred;
  7919. }());
  7920. BABYLON.Deferred = Deferred;
  7921. })(BABYLON || (BABYLON = {}));
  7922. //# sourceMappingURL=babylon.deferred.js.map
  7923. var BABYLON;
  7924. (function (BABYLON) {
  7925. /**
  7926. * A class serves as a medium between the observable and its observers
  7927. */
  7928. var EventState = /** @class */ (function () {
  7929. /**
  7930. * Create a new EventState
  7931. * @param mask defines the mask associated with this state
  7932. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7933. * @param target defines the original target of the state
  7934. * @param currentTarget defines the current target of the state
  7935. */
  7936. function EventState(mask, skipNextObservers, target, currentTarget) {
  7937. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7938. this.initalize(mask, skipNextObservers, target, currentTarget);
  7939. }
  7940. /**
  7941. * Initialize the current event state
  7942. * @param mask defines the mask associated with this state
  7943. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7944. * @param target defines the original target of the state
  7945. * @param currentTarget defines the current target of the state
  7946. * @returns the current event state
  7947. */
  7948. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7949. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7950. this.mask = mask;
  7951. this.skipNextObservers = skipNextObservers;
  7952. this.target = target;
  7953. this.currentTarget = currentTarget;
  7954. return this;
  7955. };
  7956. return EventState;
  7957. }());
  7958. BABYLON.EventState = EventState;
  7959. /**
  7960. * Represent an Observer registered to a given Observable object.
  7961. */
  7962. var Observer = /** @class */ (function () {
  7963. /**
  7964. * Creates a new observer
  7965. * @param callback defines the callback to call when the observer is notified
  7966. * @param mask defines the mask of the observer (used to filter notifications)
  7967. * @param scope defines the current scope used to restore the JS context
  7968. */
  7969. function Observer(
  7970. /**
  7971. * Defines the callback to call when the observer is notified
  7972. */
  7973. callback,
  7974. /**
  7975. * Defines the mask of the observer (used to filter notifications)
  7976. */
  7977. mask,
  7978. /**
  7979. * Defines the current scope used to restore the JS context
  7980. */
  7981. scope) {
  7982. if (scope === void 0) { scope = null; }
  7983. this.callback = callback;
  7984. this.mask = mask;
  7985. this.scope = scope;
  7986. /** @ignore */
  7987. this._willBeUnregistered = false;
  7988. /**
  7989. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7990. */
  7991. this.unregisterOnNextCall = false;
  7992. }
  7993. return Observer;
  7994. }());
  7995. BABYLON.Observer = Observer;
  7996. /**
  7997. * Represent a list of observers registered to multiple Observables object.
  7998. */
  7999. var MultiObserver = /** @class */ (function () {
  8000. function MultiObserver() {
  8001. }
  8002. /**
  8003. * Release associated resources
  8004. */
  8005. MultiObserver.prototype.dispose = function () {
  8006. if (this._observers && this._observables) {
  8007. for (var index = 0; index < this._observers.length; index++) {
  8008. this._observables[index].remove(this._observers[index]);
  8009. }
  8010. }
  8011. this._observers = null;
  8012. this._observables = null;
  8013. };
  8014. /**
  8015. * Raise a callback when one of the observable will notify
  8016. * @param observables defines a list of observables to watch
  8017. * @param callback defines the callback to call on notification
  8018. * @param mask defines the mask used to filter notifications
  8019. * @param scope defines the current scope used to restore the JS context
  8020. * @returns the new MultiObserver
  8021. */
  8022. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8023. if (mask === void 0) { mask = -1; }
  8024. if (scope === void 0) { scope = null; }
  8025. var result = new MultiObserver();
  8026. result._observers = new Array();
  8027. result._observables = observables;
  8028. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8029. var observable = observables_1[_i];
  8030. var observer = observable.add(callback, mask, false, scope);
  8031. if (observer) {
  8032. result._observers.push(observer);
  8033. }
  8034. }
  8035. return result;
  8036. };
  8037. return MultiObserver;
  8038. }());
  8039. BABYLON.MultiObserver = MultiObserver;
  8040. /**
  8041. * The Observable class is a simple implementation of the Observable pattern.
  8042. *
  8043. * 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.
  8044. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8045. * 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).
  8046. * 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.
  8047. */
  8048. var Observable = /** @class */ (function () {
  8049. /**
  8050. * Creates a new observable
  8051. * @param onObserverAdded defines a callback to call when a new observer is added
  8052. */
  8053. function Observable(onObserverAdded) {
  8054. this._observers = new Array();
  8055. this._eventState = new EventState(0);
  8056. if (onObserverAdded) {
  8057. this._onObserverAdded = onObserverAdded;
  8058. }
  8059. }
  8060. /**
  8061. * Create a new Observer with the specified callback
  8062. * @param callback the callback that will be executed for that Observer
  8063. * @param mask the mask used to filter observers
  8064. * @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.
  8065. * @param scope optional scope for the callback to be called from
  8066. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8067. * @returns the new observer created for the callback
  8068. */
  8069. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8070. if (mask === void 0) { mask = -1; }
  8071. if (insertFirst === void 0) { insertFirst = false; }
  8072. if (scope === void 0) { scope = null; }
  8073. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8074. if (!callback) {
  8075. return null;
  8076. }
  8077. var observer = new Observer(callback, mask, scope);
  8078. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8079. if (insertFirst) {
  8080. this._observers.unshift(observer);
  8081. }
  8082. else {
  8083. this._observers.push(observer);
  8084. }
  8085. if (this._onObserverAdded) {
  8086. this._onObserverAdded(observer);
  8087. }
  8088. return observer;
  8089. };
  8090. /**
  8091. * Remove an Observer from the Observable object
  8092. * @param observer the instance of the Observer to remove
  8093. * @returns false if it doesn't belong to this Observable
  8094. */
  8095. Observable.prototype.remove = function (observer) {
  8096. if (!observer) {
  8097. return false;
  8098. }
  8099. var index = this._observers.indexOf(observer);
  8100. if (index !== -1) {
  8101. this._observers.splice(index, 1);
  8102. return true;
  8103. }
  8104. return false;
  8105. };
  8106. /**
  8107. * Remove a callback from the Observable object
  8108. * @param callback the callback to remove
  8109. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8110. * @returns false if it doesn't belong to this Observable
  8111. */
  8112. Observable.prototype.removeCallback = function (callback, scope) {
  8113. for (var index = 0; index < this._observers.length; index++) {
  8114. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8115. this._observers.splice(index, 1);
  8116. return true;
  8117. }
  8118. }
  8119. return false;
  8120. };
  8121. Observable.prototype._deferUnregister = function (observer) {
  8122. var _this = this;
  8123. observer.unregisterOnNextCall = false;
  8124. observer._willBeUnregistered = true;
  8125. BABYLON.Tools.SetImmediate(function () {
  8126. _this.remove(observer);
  8127. });
  8128. };
  8129. /**
  8130. * Notify all Observers by calling their respective callback with the given data
  8131. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8132. * @param eventData defines the data to send to all observers
  8133. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8134. * @param target defines the original target of the state
  8135. * @param currentTarget defines the current target of the state
  8136. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8137. */
  8138. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8139. if (mask === void 0) { mask = -1; }
  8140. if (!this._observers.length) {
  8141. return true;
  8142. }
  8143. var state = this._eventState;
  8144. state.mask = mask;
  8145. state.target = target;
  8146. state.currentTarget = currentTarget;
  8147. state.skipNextObservers = false;
  8148. state.lastReturnValue = eventData;
  8149. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8150. var obs = _a[_i];
  8151. if (obs._willBeUnregistered) {
  8152. continue;
  8153. }
  8154. if (obs.mask & mask) {
  8155. if (obs.scope) {
  8156. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8157. }
  8158. else {
  8159. state.lastReturnValue = obs.callback(eventData, state);
  8160. }
  8161. if (obs.unregisterOnNextCall) {
  8162. this._deferUnregister(obs);
  8163. }
  8164. }
  8165. if (state.skipNextObservers) {
  8166. return false;
  8167. }
  8168. }
  8169. return true;
  8170. };
  8171. /**
  8172. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8173. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8174. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8175. * and it is crucial that all callbacks will be executed.
  8176. * The order of the callbacks is kept, callbacks are not executed parallel.
  8177. *
  8178. * @param eventData The data to be sent to each callback
  8179. * @param mask is used to filter observers defaults to -1
  8180. * @param target defines the callback target (see EventState)
  8181. * @param currentTarget defines he current object in the bubbling phase
  8182. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8183. */
  8184. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8185. var _this = this;
  8186. if (mask === void 0) { mask = -1; }
  8187. // create an empty promise
  8188. var p = Promise.resolve(eventData);
  8189. // no observers? return this promise.
  8190. if (!this._observers.length) {
  8191. return p;
  8192. }
  8193. var state = this._eventState;
  8194. state.mask = mask;
  8195. state.target = target;
  8196. state.currentTarget = currentTarget;
  8197. state.skipNextObservers = false;
  8198. // execute one callback after another (not using Promise.all, the order is important)
  8199. this._observers.forEach(function (obs) {
  8200. if (state.skipNextObservers) {
  8201. return;
  8202. }
  8203. if (obs._willBeUnregistered) {
  8204. return;
  8205. }
  8206. if (obs.mask & mask) {
  8207. if (obs.scope) {
  8208. p = p.then(function (lastReturnedValue) {
  8209. state.lastReturnValue = lastReturnedValue;
  8210. return obs.callback.apply(obs.scope, [eventData, state]);
  8211. });
  8212. }
  8213. else {
  8214. p = p.then(function (lastReturnedValue) {
  8215. state.lastReturnValue = lastReturnedValue;
  8216. return obs.callback(eventData, state);
  8217. });
  8218. }
  8219. if (obs.unregisterOnNextCall) {
  8220. _this._deferUnregister(obs);
  8221. }
  8222. }
  8223. });
  8224. // return the eventData
  8225. return p.then(function () { return eventData; });
  8226. };
  8227. /**
  8228. * Notify a specific observer
  8229. * @param observer defines the observer to notify
  8230. * @param eventData defines the data to be sent to each callback
  8231. * @param mask is used to filter observers defaults to -1
  8232. */
  8233. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8234. if (mask === void 0) { mask = -1; }
  8235. var state = this._eventState;
  8236. state.mask = mask;
  8237. state.skipNextObservers = false;
  8238. observer.callback(eventData, state);
  8239. };
  8240. /**
  8241. * Gets a boolean indicating if the observable has at least one observer
  8242. * @returns true is the Observable has at least one Observer registered
  8243. */
  8244. Observable.prototype.hasObservers = function () {
  8245. return this._observers.length > 0;
  8246. };
  8247. /**
  8248. * Clear the list of observers
  8249. */
  8250. Observable.prototype.clear = function () {
  8251. this._observers = new Array();
  8252. this._onObserverAdded = null;
  8253. };
  8254. /**
  8255. * Clone the current observable
  8256. * @returns a new observable
  8257. */
  8258. Observable.prototype.clone = function () {
  8259. var result = new Observable();
  8260. result._observers = this._observers.slice(0);
  8261. return result;
  8262. };
  8263. /**
  8264. * Does this observable handles observer registered with a given mask
  8265. * @param mask defines the mask to be tested
  8266. * @return whether or not one observer registered with the given mask is handeled
  8267. **/
  8268. Observable.prototype.hasSpecificMask = function (mask) {
  8269. if (mask === void 0) { mask = -1; }
  8270. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8271. var obs = _a[_i];
  8272. if (obs.mask & mask || obs.mask === mask) {
  8273. return true;
  8274. }
  8275. }
  8276. return false;
  8277. };
  8278. return Observable;
  8279. }());
  8280. BABYLON.Observable = Observable;
  8281. })(BABYLON || (BABYLON = {}));
  8282. //# sourceMappingURL=babylon.observable.js.map
  8283. var BABYLON;
  8284. (function (BABYLON) {
  8285. var SmartArray = /** @class */ (function () {
  8286. function SmartArray(capacity) {
  8287. this.length = 0;
  8288. this.data = new Array(capacity);
  8289. this._id = SmartArray._GlobalId++;
  8290. }
  8291. SmartArray.prototype.push = function (value) {
  8292. this.data[this.length++] = value;
  8293. if (this.length > this.data.length) {
  8294. this.data.length *= 2;
  8295. }
  8296. };
  8297. SmartArray.prototype.forEach = function (func) {
  8298. for (var index = 0; index < this.length; index++) {
  8299. func(this.data[index]);
  8300. }
  8301. };
  8302. SmartArray.prototype.sort = function (compareFn) {
  8303. this.data.sort(compareFn);
  8304. };
  8305. SmartArray.prototype.reset = function () {
  8306. this.length = 0;
  8307. };
  8308. SmartArray.prototype.dispose = function () {
  8309. this.reset();
  8310. if (this.data) {
  8311. this.data.length = 0;
  8312. this.data = [];
  8313. }
  8314. };
  8315. SmartArray.prototype.concat = function (array) {
  8316. if (array.length === 0) {
  8317. return;
  8318. }
  8319. if (this.length + array.length > this.data.length) {
  8320. this.data.length = (this.length + array.length) * 2;
  8321. }
  8322. for (var index = 0; index < array.length; index++) {
  8323. this.data[this.length++] = (array.data || array)[index];
  8324. }
  8325. };
  8326. SmartArray.prototype.indexOf = function (value) {
  8327. var position = this.data.indexOf(value);
  8328. if (position >= this.length) {
  8329. return -1;
  8330. }
  8331. return position;
  8332. };
  8333. SmartArray.prototype.contains = function (value) {
  8334. return this.data.indexOf(value) !== -1;
  8335. };
  8336. // Statics
  8337. SmartArray._GlobalId = 0;
  8338. return SmartArray;
  8339. }());
  8340. BABYLON.SmartArray = SmartArray;
  8341. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8342. __extends(SmartArrayNoDuplicate, _super);
  8343. function SmartArrayNoDuplicate() {
  8344. var _this = _super !== null && _super.apply(this, arguments) || this;
  8345. _this._duplicateId = 0;
  8346. return _this;
  8347. }
  8348. SmartArrayNoDuplicate.prototype.push = function (value) {
  8349. _super.prototype.push.call(this, value);
  8350. if (!value.__smartArrayFlags) {
  8351. value.__smartArrayFlags = {};
  8352. }
  8353. value.__smartArrayFlags[this._id] = this._duplicateId;
  8354. };
  8355. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8356. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8357. return false;
  8358. }
  8359. this.push(value);
  8360. return true;
  8361. };
  8362. SmartArrayNoDuplicate.prototype.reset = function () {
  8363. _super.prototype.reset.call(this);
  8364. this._duplicateId++;
  8365. };
  8366. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8367. if (array.length === 0) {
  8368. return;
  8369. }
  8370. if (this.length + array.length > this.data.length) {
  8371. this.data.length = (this.length + array.length) * 2;
  8372. }
  8373. for (var index = 0; index < array.length; index++) {
  8374. var item = (array.data || array)[index];
  8375. this.pushNoDuplicate(item);
  8376. }
  8377. };
  8378. return SmartArrayNoDuplicate;
  8379. }(SmartArray));
  8380. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8381. })(BABYLON || (BABYLON = {}));
  8382. //# sourceMappingURL=babylon.smartArray.js.map
  8383. var BABYLON;
  8384. (function (BABYLON) {
  8385. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8386. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8387. var LoadFileError = /** @class */ (function (_super) {
  8388. __extends(LoadFileError, _super);
  8389. function LoadFileError(message, request) {
  8390. var _this = _super.call(this, message) || this;
  8391. _this.request = request;
  8392. _this.name = "LoadFileError";
  8393. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8394. return _this;
  8395. }
  8396. // Polyfill for Object.setPrototypeOf if necessary.
  8397. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8398. return LoadFileError;
  8399. }(Error));
  8400. BABYLON.LoadFileError = LoadFileError;
  8401. var RetryStrategy = /** @class */ (function () {
  8402. function RetryStrategy() {
  8403. }
  8404. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8405. if (maxRetries === void 0) { maxRetries = 3; }
  8406. if (baseInterval === void 0) { baseInterval = 500; }
  8407. return function (url, request, retryIndex) {
  8408. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8409. return -1;
  8410. }
  8411. return Math.pow(2, retryIndex) * baseInterval;
  8412. };
  8413. };
  8414. return RetryStrategy;
  8415. }());
  8416. BABYLON.RetryStrategy = RetryStrategy;
  8417. // Screenshots
  8418. var screenshotCanvas;
  8419. var cloneValue = function (source, destinationObject) {
  8420. if (!source)
  8421. return null;
  8422. if (source instanceof BABYLON.Mesh) {
  8423. return null;
  8424. }
  8425. if (source instanceof BABYLON.SubMesh) {
  8426. return source.clone(destinationObject);
  8427. }
  8428. else if (source.clone) {
  8429. return source.clone();
  8430. }
  8431. return null;
  8432. };
  8433. var Tools = /** @class */ (function () {
  8434. function Tools() {
  8435. }
  8436. /**
  8437. * Interpolates between a and b via alpha
  8438. * @param a The lower value (returned when alpha = 0)
  8439. * @param b The upper value (returned when alpha = 1)
  8440. * @param alpha The interpolation-factor
  8441. * @return The mixed value
  8442. */
  8443. Tools.Mix = function (a, b, alpha) {
  8444. return a * (1 - alpha) + b * alpha;
  8445. };
  8446. Tools.Instantiate = function (className) {
  8447. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8448. return Tools.RegisteredExternalClasses[className];
  8449. }
  8450. var arr = className.split(".");
  8451. var fn = (window || this);
  8452. for (var i = 0, len = arr.length; i < len; i++) {
  8453. fn = fn[arr[i]];
  8454. }
  8455. if (typeof fn !== "function") {
  8456. return null;
  8457. }
  8458. return fn;
  8459. };
  8460. /**
  8461. * Provides a slice function that will work even on IE
  8462. * @param data defines the array to slice
  8463. * @param start defines the start of the data (optional)
  8464. * @param end defines the end of the data (optional)
  8465. * @returns the new sliced array
  8466. */
  8467. Tools.Slice = function (data, start, end) {
  8468. if (data.slice) {
  8469. return data.slice(start, end);
  8470. }
  8471. return Array.prototype.slice.call(data, start, end);
  8472. };
  8473. Tools.SetImmediate = function (action) {
  8474. if (window.setImmediate) {
  8475. window.setImmediate(action);
  8476. }
  8477. else {
  8478. setTimeout(action, 1);
  8479. }
  8480. };
  8481. Tools.IsExponentOfTwo = function (value) {
  8482. var count = 1;
  8483. do {
  8484. count *= 2;
  8485. } while (count < value);
  8486. return count === value;
  8487. };
  8488. /**
  8489. * Find the next highest power of two.
  8490. * @param x Number to start search from.
  8491. * @return Next highest power of two.
  8492. */
  8493. Tools.CeilingPOT = function (x) {
  8494. x--;
  8495. x |= x >> 1;
  8496. x |= x >> 2;
  8497. x |= x >> 4;
  8498. x |= x >> 8;
  8499. x |= x >> 16;
  8500. x++;
  8501. return x;
  8502. };
  8503. /**
  8504. * Find the next lowest power of two.
  8505. * @param x Number to start search from.
  8506. * @return Next lowest power of two.
  8507. */
  8508. Tools.FloorPOT = function (x) {
  8509. x = x | (x >> 1);
  8510. x = x | (x >> 2);
  8511. x = x | (x >> 4);
  8512. x = x | (x >> 8);
  8513. x = x | (x >> 16);
  8514. return x - (x >> 1);
  8515. };
  8516. /**
  8517. * Find the nearest power of two.
  8518. * @param x Number to start search from.
  8519. * @return Next nearest power of two.
  8520. */
  8521. Tools.NearestPOT = function (x) {
  8522. var c = Tools.CeilingPOT(x);
  8523. var f = Tools.FloorPOT(x);
  8524. return (c - x) > (x - f) ? f : c;
  8525. };
  8526. Tools.GetExponentOfTwo = function (value, max, mode) {
  8527. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8528. var pot;
  8529. switch (mode) {
  8530. case BABYLON.Engine.SCALEMODE_FLOOR:
  8531. pot = Tools.FloorPOT(value);
  8532. break;
  8533. case BABYLON.Engine.SCALEMODE_NEAREST:
  8534. pot = Tools.NearestPOT(value);
  8535. break;
  8536. case BABYLON.Engine.SCALEMODE_CEILING:
  8537. default:
  8538. pot = Tools.CeilingPOT(value);
  8539. break;
  8540. }
  8541. return Math.min(pot, max);
  8542. };
  8543. Tools.GetFilename = function (path) {
  8544. var index = path.lastIndexOf("/");
  8545. if (index < 0)
  8546. return path;
  8547. return path.substring(index + 1);
  8548. };
  8549. /**
  8550. * Extracts the "folder" part of a path (everything before the filename).
  8551. * @param uri The URI to extract the info from
  8552. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8553. * @returns The "folder" part of the path
  8554. */
  8555. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8556. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8557. var index = uri.lastIndexOf("/");
  8558. if (index < 0) {
  8559. if (returnUnchangedIfNoSlash) {
  8560. return uri;
  8561. }
  8562. return "";
  8563. }
  8564. return uri.substring(0, index + 1);
  8565. };
  8566. Tools.GetDOMTextContent = function (element) {
  8567. var result = "";
  8568. var child = element.firstChild;
  8569. while (child) {
  8570. if (child.nodeType === 3) {
  8571. result += child.textContent;
  8572. }
  8573. child = child.nextSibling;
  8574. }
  8575. return result;
  8576. };
  8577. Tools.ToDegrees = function (angle) {
  8578. return angle * 180 / Math.PI;
  8579. };
  8580. Tools.ToRadians = function (angle) {
  8581. return angle * Math.PI / 180;
  8582. };
  8583. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8584. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8585. var output = "";
  8586. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8587. var i = 0;
  8588. var bytes = new Uint8Array(buffer);
  8589. while (i < bytes.length) {
  8590. chr1 = bytes[i++];
  8591. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8592. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8593. enc1 = chr1 >> 2;
  8594. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8595. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8596. enc4 = chr3 & 63;
  8597. if (isNaN(chr2)) {
  8598. enc3 = enc4 = 64;
  8599. }
  8600. else if (isNaN(chr3)) {
  8601. enc4 = 64;
  8602. }
  8603. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8604. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8605. }
  8606. return "data:image/png;base64," + output;
  8607. };
  8608. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8609. if (bias === void 0) { bias = null; }
  8610. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8611. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8612. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8613. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8614. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8615. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8616. }
  8617. if (bias) {
  8618. minimum.x -= minimum.x * bias.x + bias.y;
  8619. minimum.y -= minimum.y * bias.x + bias.y;
  8620. minimum.z -= minimum.z * bias.x + bias.y;
  8621. maximum.x += maximum.x * bias.x + bias.y;
  8622. maximum.y += maximum.y * bias.x + bias.y;
  8623. maximum.z += maximum.z * bias.x + bias.y;
  8624. }
  8625. return {
  8626. minimum: minimum,
  8627. maximum: maximum
  8628. };
  8629. };
  8630. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8631. if (bias === void 0) { bias = null; }
  8632. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8633. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8634. if (!stride) {
  8635. stride = 3;
  8636. }
  8637. for (var index = start; index < start + count; index++) {
  8638. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8639. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8640. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8641. }
  8642. if (bias) {
  8643. minimum.x -= minimum.x * bias.x + bias.y;
  8644. minimum.y -= minimum.y * bias.x + bias.y;
  8645. minimum.z -= minimum.z * bias.x + bias.y;
  8646. maximum.x += maximum.x * bias.x + bias.y;
  8647. maximum.y += maximum.y * bias.x + bias.y;
  8648. maximum.z += maximum.z * bias.x + bias.y;
  8649. }
  8650. return {
  8651. minimum: minimum,
  8652. maximum: maximum
  8653. };
  8654. };
  8655. Tools.Vector2ArrayFeeder = function (array) {
  8656. return function (index) {
  8657. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8658. var length = isFloatArray ? array.length / 2 : array.length;
  8659. if (index >= length) {
  8660. return null;
  8661. }
  8662. if (isFloatArray) {
  8663. var fa = array;
  8664. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8665. }
  8666. var a = array;
  8667. return a[index];
  8668. };
  8669. };
  8670. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8671. if (bias === void 0) { bias = null; }
  8672. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8673. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8674. var i = 0;
  8675. var cur = feeder(i++);
  8676. while (cur) {
  8677. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8678. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8679. cur = feeder(i++);
  8680. }
  8681. if (bias) {
  8682. minimum.x -= minimum.x * bias.x + bias.y;
  8683. minimum.y -= minimum.y * bias.x + bias.y;
  8684. maximum.x += maximum.x * bias.x + bias.y;
  8685. maximum.y += maximum.y * bias.x + bias.y;
  8686. }
  8687. return {
  8688. minimum: minimum,
  8689. maximum: maximum
  8690. };
  8691. };
  8692. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8693. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8694. return null;
  8695. return Array.isArray(obj) ? obj : [obj];
  8696. };
  8697. // Misc.
  8698. Tools.GetPointerPrefix = function () {
  8699. var eventPrefix = "pointer";
  8700. // Check if pointer events are supported
  8701. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8702. eventPrefix = "mouse";
  8703. }
  8704. return eventPrefix;
  8705. };
  8706. /**
  8707. * @param func - the function to be called
  8708. * @param requester - the object that will request the next frame. Falls back to window.
  8709. */
  8710. Tools.QueueNewFrame = function (func, requester) {
  8711. if (!Tools.IsWindowObjectExist()) {
  8712. return setTimeout(func, 16);
  8713. }
  8714. if (!requester) {
  8715. requester = window;
  8716. }
  8717. if (requester.requestAnimationFrame) {
  8718. return requester.requestAnimationFrame(func);
  8719. }
  8720. else if (requester.msRequestAnimationFrame) {
  8721. return requester.msRequestAnimationFrame(func);
  8722. }
  8723. else if (requester.webkitRequestAnimationFrame) {
  8724. return requester.webkitRequestAnimationFrame(func);
  8725. }
  8726. else if (requester.mozRequestAnimationFrame) {
  8727. return requester.mozRequestAnimationFrame(func);
  8728. }
  8729. else if (requester.oRequestAnimationFrame) {
  8730. return requester.oRequestAnimationFrame(func);
  8731. }
  8732. else {
  8733. return window.setTimeout(func, 16);
  8734. }
  8735. };
  8736. Tools.RequestFullscreen = function (element) {
  8737. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8738. if (!requestFunction)
  8739. return;
  8740. requestFunction.call(element);
  8741. };
  8742. Tools.ExitFullscreen = function () {
  8743. if (document.exitFullscreen) {
  8744. document.exitFullscreen();
  8745. }
  8746. else if (document.mozCancelFullScreen) {
  8747. document.mozCancelFullScreen();
  8748. }
  8749. else if (document.webkitCancelFullScreen) {
  8750. document.webkitCancelFullScreen();
  8751. }
  8752. else if (document.msCancelFullScreen) {
  8753. document.msCancelFullScreen();
  8754. }
  8755. };
  8756. Tools.SetCorsBehavior = function (url, element) {
  8757. if (url && url.indexOf("data:") === 0) {
  8758. return;
  8759. }
  8760. if (Tools.CorsBehavior) {
  8761. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8762. element.crossOrigin = Tools.CorsBehavior;
  8763. }
  8764. else {
  8765. var result = Tools.CorsBehavior(url);
  8766. if (result) {
  8767. element.crossOrigin = result;
  8768. }
  8769. }
  8770. }
  8771. };
  8772. // External files
  8773. Tools.CleanUrl = function (url) {
  8774. url = url.replace(/#/mg, "%23");
  8775. return url;
  8776. };
  8777. Tools.LoadImage = function (url, onLoad, onError, database) {
  8778. if (url instanceof ArrayBuffer) {
  8779. url = Tools.EncodeArrayBufferTobase64(url);
  8780. }
  8781. url = Tools.CleanUrl(url);
  8782. url = Tools.PreprocessUrl(url);
  8783. var img = new Image();
  8784. Tools.SetCorsBehavior(url, img);
  8785. var loadHandler = function () {
  8786. img.removeEventListener("load", loadHandler);
  8787. img.removeEventListener("error", errorHandler);
  8788. onLoad(img);
  8789. };
  8790. var errorHandler = function (err) {
  8791. img.removeEventListener("load", loadHandler);
  8792. img.removeEventListener("error", errorHandler);
  8793. Tools.Error("Error while trying to load image: " + url);
  8794. if (onError) {
  8795. onError("Error while trying to load image: " + url, err);
  8796. }
  8797. };
  8798. img.addEventListener("load", loadHandler);
  8799. img.addEventListener("error", errorHandler);
  8800. var noIndexedDB = function () {
  8801. img.src = url;
  8802. };
  8803. var loadFromIndexedDB = function () {
  8804. if (database) {
  8805. database.loadImageFromDB(url, img);
  8806. }
  8807. };
  8808. //ANY database to do!
  8809. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8810. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8811. }
  8812. else {
  8813. if (url.indexOf("file:") !== -1) {
  8814. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8815. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8816. try {
  8817. var blobURL;
  8818. try {
  8819. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8820. }
  8821. catch (ex) {
  8822. // Chrome doesn't support oneTimeOnly parameter
  8823. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8824. }
  8825. img.src = blobURL;
  8826. }
  8827. catch (e) {
  8828. img.src = "";
  8829. }
  8830. return img;
  8831. }
  8832. }
  8833. noIndexedDB();
  8834. }
  8835. return img;
  8836. };
  8837. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8838. url = Tools.CleanUrl(url);
  8839. url = Tools.PreprocessUrl(url);
  8840. // If file and file input are set
  8841. if (url.indexOf("file:") !== -1) {
  8842. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8843. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8844. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8845. }
  8846. }
  8847. var loadUrl = Tools.BaseUrl + url;
  8848. var aborted = false;
  8849. var fileRequest = {
  8850. onCompleteObservable: new BABYLON.Observable(),
  8851. abort: function () { return aborted = true; },
  8852. };
  8853. var requestFile = function () {
  8854. var request = new XMLHttpRequest();
  8855. var retryHandle = null;
  8856. fileRequest.abort = function () {
  8857. aborted = true;
  8858. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8859. request.abort();
  8860. }
  8861. if (retryHandle !== null) {
  8862. clearTimeout(retryHandle);
  8863. retryHandle = null;
  8864. }
  8865. };
  8866. var retryLoop = function (retryIndex) {
  8867. request.open('GET', loadUrl, true);
  8868. if (useArrayBuffer) {
  8869. request.responseType = "arraybuffer";
  8870. }
  8871. if (onProgress) {
  8872. request.addEventListener("progress", onProgress);
  8873. }
  8874. var onLoadEnd = function () {
  8875. request.removeEventListener("loadend", onLoadEnd);
  8876. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8877. fileRequest.onCompleteObservable.clear();
  8878. };
  8879. request.addEventListener("loadend", onLoadEnd);
  8880. var onReadyStateChange = function () {
  8881. if (aborted) {
  8882. return;
  8883. }
  8884. // In case of undefined state in some browsers.
  8885. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8886. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8887. request.removeEventListener("readystatechange", onReadyStateChange);
  8888. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8889. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8890. return;
  8891. }
  8892. var retryStrategy = Tools.DefaultRetryStrategy;
  8893. if (retryStrategy) {
  8894. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8895. if (waitTime !== -1) {
  8896. // Prevent the request from completing for retry.
  8897. request.removeEventListener("loadend", onLoadEnd);
  8898. request = new XMLHttpRequest();
  8899. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8900. return;
  8901. }
  8902. }
  8903. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8904. if (onError) {
  8905. onError(request, e);
  8906. }
  8907. else {
  8908. throw e;
  8909. }
  8910. }
  8911. };
  8912. request.addEventListener("readystatechange", onReadyStateChange);
  8913. request.send();
  8914. };
  8915. retryLoop(0);
  8916. };
  8917. // Caching all files
  8918. if (database && database.enableSceneOffline) {
  8919. var noIndexedDB_1 = function () {
  8920. if (!aborted) {
  8921. requestFile();
  8922. }
  8923. };
  8924. var loadFromIndexedDB = function () {
  8925. // TODO: database needs to support aborting and should return a IFileRequest
  8926. if (aborted) {
  8927. return;
  8928. }
  8929. if (database) {
  8930. database.loadFileFromDB(url, function (data) {
  8931. if (!aborted) {
  8932. onSuccess(data);
  8933. }
  8934. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8935. }, onProgress ? function (event) {
  8936. if (!aborted) {
  8937. onProgress(event);
  8938. }
  8939. } : undefined, noIndexedDB_1, useArrayBuffer);
  8940. }
  8941. };
  8942. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8943. }
  8944. else {
  8945. requestFile();
  8946. }
  8947. return fileRequest;
  8948. };
  8949. /**
  8950. * Load a script (identified by an url). When the url returns, the
  8951. * content of this file is added into a new script element, attached to the DOM (body element)
  8952. */
  8953. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8954. var head = document.getElementsByTagName('head')[0];
  8955. var script = document.createElement('script');
  8956. script.type = 'text/javascript';
  8957. script.src = scriptUrl;
  8958. script.onload = function () {
  8959. if (onSuccess) {
  8960. onSuccess();
  8961. }
  8962. };
  8963. script.onerror = function (e) {
  8964. if (onError) {
  8965. onError("Unable to load script '" + scriptUrl + "'", e);
  8966. }
  8967. };
  8968. head.appendChild(script);
  8969. };
  8970. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8971. var reader = new FileReader();
  8972. var request = {
  8973. onCompleteObservable: new BABYLON.Observable(),
  8974. abort: function () { return reader.abort(); },
  8975. };
  8976. reader.onloadend = function (e) {
  8977. request.onCompleteObservable.notifyObservers(request);
  8978. };
  8979. reader.onload = function (e) {
  8980. //target doesn't have result from ts 1.3
  8981. callback(e.target['result']);
  8982. };
  8983. reader.onprogress = progressCallback;
  8984. reader.readAsDataURL(fileToLoad);
  8985. return request;
  8986. };
  8987. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8988. var reader = new FileReader();
  8989. var request = {
  8990. onCompleteObservable: new BABYLON.Observable(),
  8991. abort: function () { return reader.abort(); },
  8992. };
  8993. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8994. reader.onerror = function (e) {
  8995. Tools.Log("Error while reading file: " + fileToLoad.name);
  8996. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8997. };
  8998. reader.onload = function (e) {
  8999. //target doesn't have result from ts 1.3
  9000. callback(e.target['result']);
  9001. };
  9002. if (progressCallBack) {
  9003. reader.onprogress = progressCallBack;
  9004. }
  9005. if (!useArrayBuffer) {
  9006. // Asynchronous read
  9007. reader.readAsText(fileToLoad);
  9008. }
  9009. else {
  9010. reader.readAsArrayBuffer(fileToLoad);
  9011. }
  9012. return request;
  9013. };
  9014. //returns a downloadable url to a file content.
  9015. Tools.FileAsURL = function (content) {
  9016. var fileBlob = new Blob([content]);
  9017. var url = window.URL || window.webkitURL;
  9018. var link = url.createObjectURL(fileBlob);
  9019. return link;
  9020. };
  9021. // Misc.
  9022. Tools.Format = function (value, decimals) {
  9023. if (decimals === void 0) { decimals = 2; }
  9024. return value.toFixed(decimals);
  9025. };
  9026. Tools.CheckExtends = function (v, min, max) {
  9027. if (v.x < min.x)
  9028. min.x = v.x;
  9029. if (v.y < min.y)
  9030. min.y = v.y;
  9031. if (v.z < min.z)
  9032. min.z = v.z;
  9033. if (v.x > max.x)
  9034. max.x = v.x;
  9035. if (v.y > max.y)
  9036. max.y = v.y;
  9037. if (v.z > max.z)
  9038. max.z = v.z;
  9039. };
  9040. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9041. for (var prop in source) {
  9042. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9043. continue;
  9044. }
  9045. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9046. continue;
  9047. }
  9048. var sourceValue = source[prop];
  9049. var typeOfSourceValue = typeof sourceValue;
  9050. if (typeOfSourceValue === "function") {
  9051. continue;
  9052. }
  9053. try {
  9054. if (typeOfSourceValue === "object") {
  9055. if (sourceValue instanceof Array) {
  9056. destination[prop] = [];
  9057. if (sourceValue.length > 0) {
  9058. if (typeof sourceValue[0] == "object") {
  9059. for (var index = 0; index < sourceValue.length; index++) {
  9060. var clonedValue = cloneValue(sourceValue[index], destination);
  9061. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9062. destination[prop].push(clonedValue);
  9063. }
  9064. }
  9065. }
  9066. else {
  9067. destination[prop] = sourceValue.slice(0);
  9068. }
  9069. }
  9070. }
  9071. else {
  9072. destination[prop] = cloneValue(sourceValue, destination);
  9073. }
  9074. }
  9075. else {
  9076. destination[prop] = sourceValue;
  9077. }
  9078. }
  9079. catch (e) {
  9080. // Just ignore error (it could be because of a read-only property)
  9081. }
  9082. }
  9083. };
  9084. Tools.IsEmpty = function (obj) {
  9085. for (var i in obj) {
  9086. if (obj.hasOwnProperty(i)) {
  9087. return false;
  9088. }
  9089. }
  9090. return true;
  9091. };
  9092. Tools.RegisterTopRootEvents = function (events) {
  9093. for (var index = 0; index < events.length; index++) {
  9094. var event = events[index];
  9095. window.addEventListener(event.name, event.handler, false);
  9096. try {
  9097. if (window.parent) {
  9098. window.parent.addEventListener(event.name, event.handler, false);
  9099. }
  9100. }
  9101. catch (e) {
  9102. // Silently fails...
  9103. }
  9104. }
  9105. };
  9106. Tools.UnregisterTopRootEvents = function (events) {
  9107. for (var index = 0; index < events.length; index++) {
  9108. var event = events[index];
  9109. window.removeEventListener(event.name, event.handler);
  9110. try {
  9111. if (window.parent) {
  9112. window.parent.removeEventListener(event.name, event.handler);
  9113. }
  9114. }
  9115. catch (e) {
  9116. // Silently fails...
  9117. }
  9118. }
  9119. };
  9120. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9121. if (mimeType === void 0) { mimeType = "image/png"; }
  9122. // Read the contents of the framebuffer
  9123. var numberOfChannelsByLine = width * 4;
  9124. var halfHeight = height / 2;
  9125. //Reading datas from WebGL
  9126. var data = engine.readPixels(0, 0, width, height);
  9127. //To flip image on Y axis.
  9128. for (var i = 0; i < halfHeight; i++) {
  9129. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9130. var currentCell = j + i * numberOfChannelsByLine;
  9131. var targetLine = height - i - 1;
  9132. var targetCell = j + targetLine * numberOfChannelsByLine;
  9133. var temp = data[currentCell];
  9134. data[currentCell] = data[targetCell];
  9135. data[targetCell] = temp;
  9136. }
  9137. }
  9138. // Create a 2D canvas to store the result
  9139. if (!screenshotCanvas) {
  9140. screenshotCanvas = document.createElement('canvas');
  9141. }
  9142. screenshotCanvas.width = width;
  9143. screenshotCanvas.height = height;
  9144. var context = screenshotCanvas.getContext('2d');
  9145. if (context) {
  9146. // Copy the pixels to a 2D canvas
  9147. var imageData = context.createImageData(width, height);
  9148. var castData = (imageData.data);
  9149. castData.set(data);
  9150. context.putImageData(imageData, 0, 0);
  9151. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9152. }
  9153. };
  9154. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9155. if (mimeType === void 0) { mimeType = "image/png"; }
  9156. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9157. if (successCallback) {
  9158. successCallback(base64Image);
  9159. }
  9160. else {
  9161. // We need HTMLCanvasElement.toBlob for HD screenshots
  9162. if (!screenshotCanvas.toBlob) {
  9163. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9164. screenshotCanvas.toBlob = function (callback, type, quality) {
  9165. var _this = this;
  9166. setTimeout(function () {
  9167. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9168. for (var i = 0; i < len; i++) {
  9169. arr[i] = binStr.charCodeAt(i);
  9170. }
  9171. callback(new Blob([arr], { type: type || 'image/png' }));
  9172. });
  9173. };
  9174. }
  9175. screenshotCanvas.toBlob(function (blob) {
  9176. var url = URL.createObjectURL(blob);
  9177. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9178. if (("download" in document.createElement("a"))) {
  9179. var a = window.document.createElement("a");
  9180. a.href = url;
  9181. if (fileName) {
  9182. a.setAttribute("download", fileName);
  9183. }
  9184. else {
  9185. var date = new Date();
  9186. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9187. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9188. }
  9189. window.document.body.appendChild(a);
  9190. a.addEventListener("click", function () {
  9191. if (a.parentElement) {
  9192. a.parentElement.removeChild(a);
  9193. }
  9194. });
  9195. a.click();
  9196. }
  9197. else {
  9198. var newWindow = window.open("");
  9199. if (!newWindow)
  9200. return;
  9201. var img = newWindow.document.createElement("img");
  9202. img.onload = function () {
  9203. // no longer need to read the blob so it's revoked
  9204. URL.revokeObjectURL(url);
  9205. };
  9206. img.src = url;
  9207. newWindow.document.body.appendChild(img);
  9208. }
  9209. });
  9210. }
  9211. };
  9212. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9213. if (mimeType === void 0) { mimeType = "image/png"; }
  9214. var width;
  9215. var height;
  9216. // If a precision value is specified
  9217. if (size.precision) {
  9218. width = Math.round(engine.getRenderWidth() * size.precision);
  9219. height = Math.round(width / engine.getAspectRatio(camera));
  9220. }
  9221. else if (size.width && size.height) {
  9222. width = size.width;
  9223. height = size.height;
  9224. }
  9225. //If passing only width, computing height to keep display canvas ratio.
  9226. else if (size.width && !size.height) {
  9227. width = size.width;
  9228. height = Math.round(width / engine.getAspectRatio(camera));
  9229. }
  9230. //If passing only height, computing width to keep display canvas ratio.
  9231. else if (size.height && !size.width) {
  9232. height = size.height;
  9233. width = Math.round(height * engine.getAspectRatio(camera));
  9234. }
  9235. //Assuming here that "size" parameter is a number
  9236. else if (!isNaN(size)) {
  9237. height = size;
  9238. width = size;
  9239. }
  9240. else {
  9241. Tools.Error("Invalid 'size' parameter !");
  9242. return;
  9243. }
  9244. if (!screenshotCanvas) {
  9245. screenshotCanvas = document.createElement('canvas');
  9246. }
  9247. screenshotCanvas.width = width;
  9248. screenshotCanvas.height = height;
  9249. var renderContext = screenshotCanvas.getContext("2d");
  9250. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9251. var newWidth = width;
  9252. var newHeight = newWidth / ratio;
  9253. if (newHeight > height) {
  9254. newHeight = height;
  9255. newWidth = newHeight * ratio;
  9256. }
  9257. var offsetX = Math.max(0, width - newWidth) / 2;
  9258. var offsetY = Math.max(0, height - newHeight) / 2;
  9259. var renderingCanvas = engine.getRenderingCanvas();
  9260. if (renderContext && renderingCanvas) {
  9261. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9262. }
  9263. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9264. };
  9265. /**
  9266. * Generates an image screenshot from the specified camera.
  9267. *
  9268. * @param engine The engine to use for rendering
  9269. * @param camera The camera to use for rendering
  9270. * @param size This parameter can be set to a single number or to an object with the
  9271. * following (optional) properties: precision, width, height. If a single number is passed,
  9272. * it will be used for both width and height. If an object is passed, the screenshot size
  9273. * will be derived from the parameters. The precision property is a multiplier allowing
  9274. * rendering at a higher or lower resolution.
  9275. * @param successCallback The callback receives a single parameter which contains the
  9276. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9277. * src parameter of an <img> to display it.
  9278. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9279. * Check your browser for supported MIME types.
  9280. * @param samples Texture samples (default: 1)
  9281. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9282. * @param fileName A name for for the downloaded file.
  9283. * @constructor
  9284. */
  9285. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9286. if (mimeType === void 0) { mimeType = "image/png"; }
  9287. if (samples === void 0) { samples = 1; }
  9288. if (antialiasing === void 0) { antialiasing = false; }
  9289. var width;
  9290. var height;
  9291. //If a precision value is specified
  9292. if (size.precision) {
  9293. width = Math.round(engine.getRenderWidth() * size.precision);
  9294. height = Math.round(width / engine.getAspectRatio(camera));
  9295. size = { width: width, height: height };
  9296. }
  9297. else if (size.width && size.height) {
  9298. width = size.width;
  9299. height = size.height;
  9300. }
  9301. //If passing only width, computing height to keep display canvas ratio.
  9302. else if (size.width && !size.height) {
  9303. width = size.width;
  9304. height = Math.round(width / engine.getAspectRatio(camera));
  9305. size = { width: width, height: height };
  9306. }
  9307. //If passing only height, computing width to keep display canvas ratio.
  9308. else if (size.height && !size.width) {
  9309. height = size.height;
  9310. width = Math.round(height * engine.getAspectRatio(camera));
  9311. size = { width: width, height: height };
  9312. }
  9313. //Assuming here that "size" parameter is a number
  9314. else if (!isNaN(size)) {
  9315. height = size;
  9316. width = size;
  9317. }
  9318. else {
  9319. Tools.Error("Invalid 'size' parameter !");
  9320. return;
  9321. }
  9322. var scene = camera.getScene();
  9323. var previousCamera = null;
  9324. if (scene.activeCamera !== camera) {
  9325. previousCamera = scene.activeCamera;
  9326. scene.activeCamera = camera;
  9327. }
  9328. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9329. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9330. texture.renderList = null;
  9331. texture.samples = samples;
  9332. if (antialiasing) {
  9333. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9334. }
  9335. texture.onAfterRenderObservable.add(function () {
  9336. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9337. });
  9338. scene.incrementRenderId();
  9339. scene.resetCachedMaterial();
  9340. texture.render(true);
  9341. texture.dispose();
  9342. if (previousCamera) {
  9343. scene.activeCamera = previousCamera;
  9344. }
  9345. camera.getProjectionMatrix(true); // Force cache refresh;
  9346. };
  9347. // XHR response validator for local file scenario
  9348. Tools.ValidateXHRData = function (xhr, dataType) {
  9349. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9350. if (dataType === void 0) { dataType = 7; }
  9351. try {
  9352. if (dataType & 1) {
  9353. if (xhr.responseText && xhr.responseText.length > 0) {
  9354. return true;
  9355. }
  9356. else if (dataType === 1) {
  9357. return false;
  9358. }
  9359. }
  9360. if (dataType & 2) {
  9361. // Check header width and height since there is no "TGA" magic number
  9362. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9363. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9364. return true;
  9365. }
  9366. else if (dataType === 2) {
  9367. return false;
  9368. }
  9369. }
  9370. if (dataType & 4) {
  9371. // Check for the "DDS" magic number
  9372. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9373. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9374. return true;
  9375. }
  9376. else {
  9377. return false;
  9378. }
  9379. }
  9380. }
  9381. catch (e) {
  9382. // Global protection
  9383. }
  9384. return false;
  9385. };
  9386. /**
  9387. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9388. * Be aware Math.random() could cause collisions, but:
  9389. * "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"
  9390. */
  9391. Tools.RandomId = function () {
  9392. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9393. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9394. return v.toString(16);
  9395. });
  9396. };
  9397. /**
  9398. * Test if the given uri is a base64 string.
  9399. * @param uri The uri to test
  9400. * @return True if the uri is a base64 string or false otherwise.
  9401. */
  9402. Tools.IsBase64 = function (uri) {
  9403. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9404. };
  9405. /**
  9406. * Decode the given base64 uri.
  9407. * @param uri The uri to decode
  9408. * @return The decoded base64 data.
  9409. */
  9410. Tools.DecodeBase64 = function (uri) {
  9411. var decodedString = atob(uri.split(",")[1]);
  9412. var bufferLength = decodedString.length;
  9413. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9414. for (var i = 0; i < bufferLength; i++) {
  9415. bufferView[i] = decodedString.charCodeAt(i);
  9416. }
  9417. return bufferView.buffer;
  9418. };
  9419. Object.defineProperty(Tools, "NoneLogLevel", {
  9420. get: function () {
  9421. return Tools._NoneLogLevel;
  9422. },
  9423. enumerable: true,
  9424. configurable: true
  9425. });
  9426. Object.defineProperty(Tools, "MessageLogLevel", {
  9427. get: function () {
  9428. return Tools._MessageLogLevel;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(Tools, "WarningLogLevel", {
  9434. get: function () {
  9435. return Tools._WarningLogLevel;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(Tools, "ErrorLogLevel", {
  9441. get: function () {
  9442. return Tools._ErrorLogLevel;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. Object.defineProperty(Tools, "AllLogLevel", {
  9448. get: function () {
  9449. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9450. },
  9451. enumerable: true,
  9452. configurable: true
  9453. });
  9454. Tools._AddLogEntry = function (entry) {
  9455. Tools._LogCache = entry + Tools._LogCache;
  9456. if (Tools.OnNewCacheEntry) {
  9457. Tools.OnNewCacheEntry(entry);
  9458. }
  9459. };
  9460. Tools._FormatMessage = function (message) {
  9461. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9462. var date = new Date();
  9463. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9464. };
  9465. Tools._LogDisabled = function (message) {
  9466. // nothing to do
  9467. };
  9468. Tools._LogEnabled = function (message) {
  9469. var formattedMessage = Tools._FormatMessage(message);
  9470. console.log("BJS - " + formattedMessage);
  9471. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9472. Tools._AddLogEntry(entry);
  9473. };
  9474. Tools._WarnDisabled = function (message) {
  9475. // nothing to do
  9476. };
  9477. Tools._WarnEnabled = function (message) {
  9478. var formattedMessage = Tools._FormatMessage(message);
  9479. console.warn("BJS - " + formattedMessage);
  9480. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9481. Tools._AddLogEntry(entry);
  9482. };
  9483. Tools._ErrorDisabled = function (message) {
  9484. // nothing to do
  9485. };
  9486. Tools._ErrorEnabled = function (message) {
  9487. Tools.errorsCount++;
  9488. var formattedMessage = Tools._FormatMessage(message);
  9489. console.error("BJS - " + formattedMessage);
  9490. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9491. Tools._AddLogEntry(entry);
  9492. };
  9493. Object.defineProperty(Tools, "LogCache", {
  9494. get: function () {
  9495. return Tools._LogCache;
  9496. },
  9497. enumerable: true,
  9498. configurable: true
  9499. });
  9500. Tools.ClearLogCache = function () {
  9501. Tools._LogCache = "";
  9502. Tools.errorsCount = 0;
  9503. };
  9504. Object.defineProperty(Tools, "LogLevels", {
  9505. set: function (level) {
  9506. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9507. Tools.Log = Tools._LogEnabled;
  9508. }
  9509. else {
  9510. Tools.Log = Tools._LogDisabled;
  9511. }
  9512. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9513. Tools.Warn = Tools._WarnEnabled;
  9514. }
  9515. else {
  9516. Tools.Warn = Tools._WarnDisabled;
  9517. }
  9518. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9519. Tools.Error = Tools._ErrorEnabled;
  9520. }
  9521. else {
  9522. Tools.Error = Tools._ErrorDisabled;
  9523. }
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Tools.IsWindowObjectExist = function () {
  9529. return (typeof window) !== "undefined";
  9530. };
  9531. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9532. get: function () {
  9533. return Tools._PerformanceNoneLogLevel;
  9534. },
  9535. enumerable: true,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9539. get: function () {
  9540. return Tools._PerformanceUserMarkLogLevel;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9546. get: function () {
  9547. return Tools._PerformanceConsoleLogLevel;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9553. set: function (level) {
  9554. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9555. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9556. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9557. return;
  9558. }
  9559. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9560. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9561. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9562. return;
  9563. }
  9564. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9565. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9571. };
  9572. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9573. };
  9574. Tools._StartUserMark = function (counterName, condition) {
  9575. if (condition === void 0) { condition = true; }
  9576. if (!Tools._performance) {
  9577. if (!Tools.IsWindowObjectExist()) {
  9578. return;
  9579. }
  9580. Tools._performance = window.performance;
  9581. }
  9582. if (!condition || !Tools._performance.mark) {
  9583. return;
  9584. }
  9585. Tools._performance.mark(counterName + "-Begin");
  9586. };
  9587. Tools._EndUserMark = function (counterName, condition) {
  9588. if (condition === void 0) { condition = true; }
  9589. if (!condition || !Tools._performance.mark) {
  9590. return;
  9591. }
  9592. Tools._performance.mark(counterName + "-End");
  9593. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9594. };
  9595. Tools._StartPerformanceConsole = function (counterName, condition) {
  9596. if (condition === void 0) { condition = true; }
  9597. if (!condition) {
  9598. return;
  9599. }
  9600. Tools._StartUserMark(counterName, condition);
  9601. if (console.time) {
  9602. console.time(counterName);
  9603. }
  9604. };
  9605. Tools._EndPerformanceConsole = function (counterName, condition) {
  9606. if (condition === void 0) { condition = true; }
  9607. if (!condition) {
  9608. return;
  9609. }
  9610. Tools._EndUserMark(counterName, condition);
  9611. if (console.time) {
  9612. console.timeEnd(counterName);
  9613. }
  9614. };
  9615. Object.defineProperty(Tools, "Now", {
  9616. get: function () {
  9617. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9618. return window.performance.now();
  9619. }
  9620. return Date.now();
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. /**
  9626. * This method will return the name of the class used to create the instance of the given object.
  9627. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9628. * @param object the object to get the class name from
  9629. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9630. */
  9631. Tools.GetClassName = function (object, isType) {
  9632. if (isType === void 0) { isType = false; }
  9633. var name = null;
  9634. if (!isType && object.getClassName) {
  9635. name = object.getClassName();
  9636. }
  9637. else {
  9638. if (object instanceof Object) {
  9639. var classObj = isType ? object : Object.getPrototypeOf(object);
  9640. name = classObj.constructor["__bjsclassName__"];
  9641. }
  9642. if (!name) {
  9643. name = typeof object;
  9644. }
  9645. }
  9646. return name;
  9647. };
  9648. Tools.First = function (array, predicate) {
  9649. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9650. var el = array_1[_i];
  9651. if (predicate(el)) {
  9652. return el;
  9653. }
  9654. }
  9655. return null;
  9656. };
  9657. /**
  9658. * This method will return the name of the full name of the class, including its owning module (if any).
  9659. * 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).
  9660. * @param object the object to get the class name from
  9661. * @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.
  9662. */
  9663. Tools.getFullClassName = function (object, isType) {
  9664. if (isType === void 0) { isType = false; }
  9665. var className = null;
  9666. var moduleName = null;
  9667. if (!isType && object.getClassName) {
  9668. className = object.getClassName();
  9669. }
  9670. else {
  9671. if (object instanceof Object) {
  9672. var classObj = isType ? object : Object.getPrototypeOf(object);
  9673. className = classObj.constructor["__bjsclassName__"];
  9674. moduleName = classObj.constructor["__bjsmoduleName__"];
  9675. }
  9676. if (!className) {
  9677. className = typeof object;
  9678. }
  9679. }
  9680. if (!className) {
  9681. return null;
  9682. }
  9683. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9684. };
  9685. /**
  9686. * 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.
  9687. * @param array
  9688. */
  9689. Tools.arrayOrStringFeeder = function (array) {
  9690. return function (index) {
  9691. if (index >= array.length) {
  9692. return null;
  9693. }
  9694. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9695. if (val && val.getHashCode) {
  9696. val = val.getHashCode();
  9697. }
  9698. if (typeof val === "string") {
  9699. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9700. }
  9701. return val;
  9702. };
  9703. };
  9704. /**
  9705. * Compute the hashCode of a stream of number
  9706. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9707. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9708. * @return the hash code computed
  9709. */
  9710. Tools.hashCodeFromStream = function (feeder) {
  9711. // Based from here: http://stackoverflow.com/a/7616484/802124
  9712. var hash = 0;
  9713. var index = 0;
  9714. var chr = feeder(index++);
  9715. while (chr != null) {
  9716. hash = ((hash << 5) - hash) + chr;
  9717. hash |= 0; // Convert to 32bit integer
  9718. chr = feeder(index++);
  9719. }
  9720. return hash;
  9721. };
  9722. /**
  9723. * Returns a promise that resolves after the given amount of time.
  9724. * @param delay Number of milliseconds to delay
  9725. * @returns Promise that resolves after the given amount of time
  9726. */
  9727. Tools.DelayAsync = function (delay) {
  9728. return new Promise(function (resolve) {
  9729. setTimeout(function () {
  9730. resolve();
  9731. }, delay);
  9732. });
  9733. };
  9734. Tools.BaseUrl = "";
  9735. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9736. /**
  9737. * Default behaviour for cors in the application.
  9738. * It can be a string if the expected behavior is identical in the entire app.
  9739. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9740. */
  9741. Tools.CorsBehavior = "anonymous";
  9742. Tools.UseFallbackTexture = true;
  9743. /**
  9744. * Use this object to register external classes like custom textures or material
  9745. * to allow the laoders to instantiate them
  9746. */
  9747. Tools.RegisteredExternalClasses = {};
  9748. // Used in case of a texture loading problem
  9749. 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";
  9750. Tools.PreprocessUrl = function (url) {
  9751. return url;
  9752. };
  9753. // Logs
  9754. Tools._NoneLogLevel = 0;
  9755. Tools._MessageLogLevel = 1;
  9756. Tools._WarningLogLevel = 2;
  9757. Tools._ErrorLogLevel = 4;
  9758. Tools._LogCache = "";
  9759. Tools.errorsCount = 0;
  9760. Tools.Log = Tools._LogEnabled;
  9761. Tools.Warn = Tools._WarnEnabled;
  9762. Tools.Error = Tools._ErrorEnabled;
  9763. // Performances
  9764. Tools._PerformanceNoneLogLevel = 0;
  9765. Tools._PerformanceUserMarkLogLevel = 1;
  9766. Tools._PerformanceConsoleLogLevel = 2;
  9767. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9768. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9769. return Tools;
  9770. }());
  9771. BABYLON.Tools = Tools;
  9772. /**
  9773. * This class is used to track a performance counter which is number based.
  9774. * The user has access to many properties which give statistics of different nature
  9775. *
  9776. * The implementer can track two kinds of Performance Counter: time and count
  9777. * 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.
  9778. * 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.
  9779. */
  9780. var PerfCounter = /** @class */ (function () {
  9781. function PerfCounter() {
  9782. this._startMonitoringTime = 0;
  9783. this._min = 0;
  9784. this._max = 0;
  9785. this._average = 0;
  9786. this._lastSecAverage = 0;
  9787. this._current = 0;
  9788. this._totalValueCount = 0;
  9789. this._totalAccumulated = 0;
  9790. this._lastSecAccumulated = 0;
  9791. this._lastSecTime = 0;
  9792. this._lastSecValueCount = 0;
  9793. }
  9794. Object.defineProperty(PerfCounter.prototype, "min", {
  9795. /**
  9796. * Returns the smallest value ever
  9797. */
  9798. get: function () {
  9799. return this._min;
  9800. },
  9801. enumerable: true,
  9802. configurable: true
  9803. });
  9804. Object.defineProperty(PerfCounter.prototype, "max", {
  9805. /**
  9806. * Returns the biggest value ever
  9807. */
  9808. get: function () {
  9809. return this._max;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. Object.defineProperty(PerfCounter.prototype, "average", {
  9815. /**
  9816. * Returns the average value since the performance counter is running
  9817. */
  9818. get: function () {
  9819. return this._average;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9825. /**
  9826. * Returns the average value of the last second the counter was monitored
  9827. */
  9828. get: function () {
  9829. return this._lastSecAverage;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(PerfCounter.prototype, "current", {
  9835. /**
  9836. * Returns the current value
  9837. */
  9838. get: function () {
  9839. return this._current;
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(PerfCounter.prototype, "total", {
  9845. get: function () {
  9846. return this._totalAccumulated;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(PerfCounter.prototype, "count", {
  9852. get: function () {
  9853. return this._totalValueCount;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. /**
  9859. * Call this method to start monitoring a new frame.
  9860. * 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.
  9861. */
  9862. PerfCounter.prototype.fetchNewFrame = function () {
  9863. this._totalValueCount++;
  9864. this._current = 0;
  9865. this._lastSecValueCount++;
  9866. };
  9867. /**
  9868. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9869. * @param newCount the count value to add to the monitored count
  9870. * @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.
  9871. */
  9872. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9873. if (!PerfCounter.Enabled) {
  9874. return;
  9875. }
  9876. this._current += newCount;
  9877. if (fetchResult) {
  9878. this._fetchResult();
  9879. }
  9880. };
  9881. /**
  9882. * Start monitoring this performance counter
  9883. */
  9884. PerfCounter.prototype.beginMonitoring = function () {
  9885. if (!PerfCounter.Enabled) {
  9886. return;
  9887. }
  9888. this._startMonitoringTime = Tools.Now;
  9889. };
  9890. /**
  9891. * Compute the time lapsed since the previous beginMonitoring() call.
  9892. * @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
  9893. */
  9894. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9895. if (newFrame === void 0) { newFrame = true; }
  9896. if (!PerfCounter.Enabled) {
  9897. return;
  9898. }
  9899. if (newFrame) {
  9900. this.fetchNewFrame();
  9901. }
  9902. var currentTime = Tools.Now;
  9903. this._current = currentTime - this._startMonitoringTime;
  9904. if (newFrame) {
  9905. this._fetchResult();
  9906. }
  9907. };
  9908. PerfCounter.prototype._fetchResult = function () {
  9909. this._totalAccumulated += this._current;
  9910. this._lastSecAccumulated += this._current;
  9911. // Min/Max update
  9912. this._min = Math.min(this._min, this._current);
  9913. this._max = Math.max(this._max, this._current);
  9914. this._average = this._totalAccumulated / this._totalValueCount;
  9915. // Reset last sec?
  9916. var now = Tools.Now;
  9917. if ((now - this._lastSecTime) > 1000) {
  9918. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9919. this._lastSecTime = now;
  9920. this._lastSecAccumulated = 0;
  9921. this._lastSecValueCount = 0;
  9922. }
  9923. };
  9924. PerfCounter.Enabled = true;
  9925. return PerfCounter;
  9926. }());
  9927. BABYLON.PerfCounter = PerfCounter;
  9928. /**
  9929. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9930. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9931. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9932. * @param name The name of the class, case should be preserved
  9933. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9934. */
  9935. function className(name, module) {
  9936. return function (target) {
  9937. target["__bjsclassName__"] = name;
  9938. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9939. };
  9940. }
  9941. BABYLON.className = className;
  9942. /**
  9943. * An implementation of a loop for asynchronous functions.
  9944. */
  9945. var AsyncLoop = /** @class */ (function () {
  9946. /**
  9947. * Constroctor.
  9948. * @param iterations the number of iterations.
  9949. * @param _fn the function to run each iteration
  9950. * @param _successCallback the callback that will be called upon succesful execution
  9951. * @param offset starting offset.
  9952. */
  9953. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9954. if (offset === void 0) { offset = 0; }
  9955. this.iterations = iterations;
  9956. this._fn = _fn;
  9957. this._successCallback = _successCallback;
  9958. this.index = offset - 1;
  9959. this._done = false;
  9960. }
  9961. /**
  9962. * Execute the next iteration. Must be called after the last iteration was finished.
  9963. */
  9964. AsyncLoop.prototype.executeNext = function () {
  9965. if (!this._done) {
  9966. if (this.index + 1 < this.iterations) {
  9967. ++this.index;
  9968. this._fn(this);
  9969. }
  9970. else {
  9971. this.breakLoop();
  9972. }
  9973. }
  9974. };
  9975. /**
  9976. * Break the loop and run the success callback.
  9977. */
  9978. AsyncLoop.prototype.breakLoop = function () {
  9979. this._done = true;
  9980. this._successCallback();
  9981. };
  9982. /**
  9983. * Helper function
  9984. */
  9985. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9986. if (offset === void 0) { offset = 0; }
  9987. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9988. loop.executeNext();
  9989. return loop;
  9990. };
  9991. /**
  9992. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9993. * @param iterations total number of iterations
  9994. * @param syncedIterations number of synchronous iterations in each async iteration.
  9995. * @param fn the function to call each iteration.
  9996. * @param callback a success call back that will be called when iterating stops.
  9997. * @param breakFunction a break condition (optional)
  9998. * @param timeout timeout settings for the setTimeout function. default - 0.
  9999. * @constructor
  10000. */
  10001. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10002. if (timeout === void 0) { timeout = 0; }
  10003. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10004. if (breakFunction && breakFunction())
  10005. loop.breakLoop();
  10006. else {
  10007. setTimeout(function () {
  10008. for (var i = 0; i < syncedIterations; ++i) {
  10009. var iteration = (loop.index * syncedIterations) + i;
  10010. if (iteration >= iterations)
  10011. break;
  10012. fn(iteration);
  10013. if (breakFunction && breakFunction()) {
  10014. loop.breakLoop();
  10015. break;
  10016. }
  10017. }
  10018. loop.executeNext();
  10019. }, timeout);
  10020. }
  10021. }, callback);
  10022. };
  10023. return AsyncLoop;
  10024. }());
  10025. BABYLON.AsyncLoop = AsyncLoop;
  10026. })(BABYLON || (BABYLON = {}));
  10027. //# sourceMappingURL=babylon.tools.js.map
  10028. var BABYLON;
  10029. (function (BABYLON) {
  10030. var PromiseStates;
  10031. (function (PromiseStates) {
  10032. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10033. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10034. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10035. })(PromiseStates || (PromiseStates = {}));
  10036. var FulFillmentAgregator = /** @class */ (function () {
  10037. function FulFillmentAgregator() {
  10038. this.count = 0;
  10039. this.target = 0;
  10040. this.results = [];
  10041. }
  10042. return FulFillmentAgregator;
  10043. }());
  10044. var InternalPromise = /** @class */ (function () {
  10045. function InternalPromise(resolver) {
  10046. var _this = this;
  10047. this._state = PromiseStates.Pending;
  10048. this._children = new Array();
  10049. this._rejectWasConsumed = false;
  10050. if (!resolver) {
  10051. return;
  10052. }
  10053. try {
  10054. resolver(function (value) {
  10055. _this._resolve(value);
  10056. }, function (reason) {
  10057. _this._reject(reason);
  10058. });
  10059. }
  10060. catch (e) {
  10061. this._reject(e);
  10062. }
  10063. }
  10064. InternalPromise.prototype.catch = function (onRejected) {
  10065. return this.then(undefined, onRejected);
  10066. };
  10067. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10068. var _this = this;
  10069. var newPromise = new InternalPromise();
  10070. newPromise._onFulfilled = onFulfilled;
  10071. newPromise._onRejected = onRejected;
  10072. // Composition
  10073. this._children.push(newPromise);
  10074. if (this._state !== PromiseStates.Pending) {
  10075. BABYLON.Tools.SetImmediate(function () {
  10076. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10077. var returnedValue = newPromise._resolve(_this._result);
  10078. if (returnedValue !== undefined && returnedValue !== null) {
  10079. if (returnedValue._state !== undefined) {
  10080. var returnedPromise = returnedValue;
  10081. newPromise._children.push(returnedPromise);
  10082. newPromise = returnedPromise;
  10083. }
  10084. else {
  10085. newPromise._result = returnedValue;
  10086. }
  10087. }
  10088. }
  10089. else {
  10090. newPromise._reject(_this._reason);
  10091. }
  10092. });
  10093. }
  10094. return newPromise;
  10095. };
  10096. InternalPromise.prototype._moveChildren = function (children) {
  10097. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10098. if (this._state === PromiseStates.Fulfilled) {
  10099. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10100. var child = _b[_i];
  10101. child._resolve(this._result);
  10102. }
  10103. }
  10104. else if (this._state === PromiseStates.Rejected) {
  10105. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10106. var child = _d[_c];
  10107. child._reject(this._reason);
  10108. }
  10109. }
  10110. var _a;
  10111. };
  10112. InternalPromise.prototype._resolve = function (value) {
  10113. try {
  10114. this._state = PromiseStates.Fulfilled;
  10115. var returnedValue = null;
  10116. if (this._onFulfilled) {
  10117. returnedValue = this._onFulfilled(value);
  10118. }
  10119. if (returnedValue !== undefined && returnedValue !== null) {
  10120. if (returnedValue._state !== undefined) {
  10121. // Transmit children
  10122. var returnedPromise = returnedValue;
  10123. returnedPromise._moveChildren(this._children);
  10124. value = returnedPromise._result;
  10125. }
  10126. else {
  10127. value = returnedValue;
  10128. }
  10129. }
  10130. this._result = value;
  10131. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10132. var child = _a[_i];
  10133. child._resolve(value);
  10134. }
  10135. this._children.length = 0;
  10136. delete this._onFulfilled;
  10137. delete this._onRejected;
  10138. }
  10139. catch (e) {
  10140. this._reject(e, true);
  10141. }
  10142. };
  10143. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10144. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10145. this._state = PromiseStates.Rejected;
  10146. this._reason = reason;
  10147. if (this._onRejected && !onLocalThrow) {
  10148. try {
  10149. this._onRejected(reason);
  10150. this._rejectWasConsumed = true;
  10151. }
  10152. catch (e) {
  10153. reason = e;
  10154. }
  10155. }
  10156. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10157. var child = _a[_i];
  10158. if (this._rejectWasConsumed) {
  10159. child._resolve(null);
  10160. }
  10161. else {
  10162. child._reject(reason);
  10163. }
  10164. }
  10165. this._children.length = 0;
  10166. delete this._onFulfilled;
  10167. delete this._onRejected;
  10168. };
  10169. InternalPromise.resolve = function (value) {
  10170. var newPromise = new InternalPromise();
  10171. newPromise._resolve(value);
  10172. return newPromise;
  10173. };
  10174. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10175. promise.then(function (value) {
  10176. agregator.results[index] = value;
  10177. agregator.count++;
  10178. if (agregator.count === agregator.target) {
  10179. agregator.rootPromise._resolve(agregator.results);
  10180. }
  10181. return null;
  10182. }, function (reason) {
  10183. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10184. agregator.rootPromise._reject(reason);
  10185. }
  10186. });
  10187. };
  10188. InternalPromise.all = function (promises) {
  10189. var newPromise = new InternalPromise();
  10190. var agregator = new FulFillmentAgregator();
  10191. agregator.target = promises.length;
  10192. agregator.rootPromise = newPromise;
  10193. if (promises.length) {
  10194. for (var index = 0; index < promises.length; index++) {
  10195. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10196. }
  10197. }
  10198. else {
  10199. newPromise._resolve([]);
  10200. }
  10201. return newPromise;
  10202. };
  10203. InternalPromise.race = function (promises) {
  10204. var newPromise = new InternalPromise();
  10205. if (promises.length) {
  10206. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10207. var promise = promises_1[_i];
  10208. promise.then(function (value) {
  10209. if (newPromise) {
  10210. newPromise._resolve(value);
  10211. newPromise = null;
  10212. }
  10213. return null;
  10214. }, function (reason) {
  10215. if (newPromise) {
  10216. newPromise._reject(reason);
  10217. newPromise = null;
  10218. }
  10219. });
  10220. }
  10221. }
  10222. return newPromise;
  10223. };
  10224. return InternalPromise;
  10225. }());
  10226. /**
  10227. * Helper class that provides a small promise polyfill
  10228. */
  10229. var PromisePolyfill = /** @class */ (function () {
  10230. function PromisePolyfill() {
  10231. }
  10232. /**
  10233. * Static function used to check if the polyfill is required
  10234. * If this is the case then the function will inject the polyfill to window.Promise
  10235. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10236. */
  10237. PromisePolyfill.Apply = function (force) {
  10238. if (force === void 0) { force = false; }
  10239. if (force || typeof Promise === 'undefined') {
  10240. var root = window;
  10241. root.Promise = InternalPromise;
  10242. }
  10243. };
  10244. return PromisePolyfill;
  10245. }());
  10246. BABYLON.PromisePolyfill = PromisePolyfill;
  10247. })(BABYLON || (BABYLON = {}));
  10248. //# sourceMappingURL=babylon.promise.js.map
  10249. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10250. var BABYLON;
  10251. (function (BABYLON) {
  10252. /**
  10253. * Helper class to push actions to a pool of workers.
  10254. */
  10255. var WorkerPool = /** @class */ (function () {
  10256. /**
  10257. * Constructor
  10258. * @param workers Array of workers to use for actions
  10259. */
  10260. function WorkerPool(workers) {
  10261. this._pendingActions = new Array();
  10262. this._workerInfos = workers.map(function (worker) { return ({
  10263. worker: worker,
  10264. active: false
  10265. }); });
  10266. }
  10267. /**
  10268. * Terminates all workers and clears any pending actions.
  10269. */
  10270. WorkerPool.prototype.dispose = function () {
  10271. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10272. var workerInfo = _a[_i];
  10273. workerInfo.worker.terminate();
  10274. }
  10275. delete this._workerInfos;
  10276. delete this._pendingActions;
  10277. };
  10278. /**
  10279. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10280. * pended until a worker has completed its action.
  10281. * @param action The action to perform. Call onComplete when the action is complete.
  10282. */
  10283. WorkerPool.prototype.push = function (action) {
  10284. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10285. var workerInfo = _a[_i];
  10286. if (!workerInfo.active) {
  10287. this._execute(workerInfo, action);
  10288. return;
  10289. }
  10290. }
  10291. this._pendingActions.push(action);
  10292. };
  10293. WorkerPool.prototype._execute = function (workerInfo, action) {
  10294. var _this = this;
  10295. workerInfo.active = true;
  10296. action(workerInfo.worker, function () {
  10297. workerInfo.active = false;
  10298. var nextAction = _this._pendingActions.shift();
  10299. if (nextAction) {
  10300. _this._execute(workerInfo, nextAction);
  10301. }
  10302. });
  10303. };
  10304. return WorkerPool;
  10305. }());
  10306. BABYLON.WorkerPool = WorkerPool;
  10307. })(BABYLON || (BABYLON = {}));
  10308. //# sourceMappingURL=babylon.workerPool.js.map
  10309. var BABYLON;
  10310. (function (BABYLON) {
  10311. var _AlphaState = /** @class */ (function () {
  10312. /**
  10313. * Initializes the state.
  10314. */
  10315. function _AlphaState() {
  10316. this._isAlphaBlendDirty = false;
  10317. this._isBlendFunctionParametersDirty = false;
  10318. this._isBlendEquationParametersDirty = false;
  10319. this._isBlendConstantsDirty = false;
  10320. this._alphaBlend = false;
  10321. this._blendFunctionParameters = new Array(4);
  10322. this._blendEquationParameters = new Array(2);
  10323. this._blendConstants = new Array(4);
  10324. this.reset();
  10325. }
  10326. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10327. get: function () {
  10328. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10329. },
  10330. enumerable: true,
  10331. configurable: true
  10332. });
  10333. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10334. get: function () {
  10335. return this._alphaBlend;
  10336. },
  10337. set: function (value) {
  10338. if (this._alphaBlend === value) {
  10339. return;
  10340. }
  10341. this._alphaBlend = value;
  10342. this._isAlphaBlendDirty = true;
  10343. },
  10344. enumerable: true,
  10345. configurable: true
  10346. });
  10347. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10348. if (this._blendConstants[0] === r &&
  10349. this._blendConstants[1] === g &&
  10350. this._blendConstants[2] === b &&
  10351. this._blendConstants[3] === a) {
  10352. return;
  10353. }
  10354. this._blendConstants[0] = r;
  10355. this._blendConstants[1] = g;
  10356. this._blendConstants[2] = b;
  10357. this._blendConstants[3] = a;
  10358. this._isBlendConstantsDirty = true;
  10359. };
  10360. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10361. if (this._blendFunctionParameters[0] === value0 &&
  10362. this._blendFunctionParameters[1] === value1 &&
  10363. this._blendFunctionParameters[2] === value2 &&
  10364. this._blendFunctionParameters[3] === value3) {
  10365. return;
  10366. }
  10367. this._blendFunctionParameters[0] = value0;
  10368. this._blendFunctionParameters[1] = value1;
  10369. this._blendFunctionParameters[2] = value2;
  10370. this._blendFunctionParameters[3] = value3;
  10371. this._isBlendFunctionParametersDirty = true;
  10372. };
  10373. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10374. if (this._blendEquationParameters[0] === rgb &&
  10375. this._blendEquationParameters[1] === alpha) {
  10376. return;
  10377. }
  10378. this._blendEquationParameters[0] = rgb;
  10379. this._blendEquationParameters[1] = alpha;
  10380. this._isBlendEquationParametersDirty = true;
  10381. };
  10382. _AlphaState.prototype.reset = function () {
  10383. this._alphaBlend = false;
  10384. this._blendFunctionParameters[0] = null;
  10385. this._blendFunctionParameters[1] = null;
  10386. this._blendFunctionParameters[2] = null;
  10387. this._blendFunctionParameters[3] = null;
  10388. this._blendEquationParameters[0] = null;
  10389. this._blendEquationParameters[1] = null;
  10390. this._blendConstants[0] = null;
  10391. this._blendConstants[1] = null;
  10392. this._blendConstants[2] = null;
  10393. this._blendConstants[3] = null;
  10394. this._isAlphaBlendDirty = true;
  10395. this._isBlendFunctionParametersDirty = false;
  10396. this._isBlendEquationParametersDirty = false;
  10397. this._isBlendConstantsDirty = false;
  10398. };
  10399. _AlphaState.prototype.apply = function (gl) {
  10400. if (!this.isDirty) {
  10401. return;
  10402. }
  10403. // Alpha blend
  10404. if (this._isAlphaBlendDirty) {
  10405. if (this._alphaBlend) {
  10406. gl.enable(gl.BLEND);
  10407. }
  10408. else {
  10409. gl.disable(gl.BLEND);
  10410. }
  10411. this._isAlphaBlendDirty = false;
  10412. }
  10413. // Alpha function
  10414. if (this._isBlendFunctionParametersDirty) {
  10415. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10416. this._isBlendFunctionParametersDirty = false;
  10417. }
  10418. // Alpha equation
  10419. if (this._isBlendEquationParametersDirty) {
  10420. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10421. this._isBlendEquationParametersDirty = false;
  10422. }
  10423. // Constants
  10424. if (this._isBlendConstantsDirty) {
  10425. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10426. this._isBlendConstantsDirty = false;
  10427. }
  10428. };
  10429. return _AlphaState;
  10430. }());
  10431. BABYLON._AlphaState = _AlphaState;
  10432. })(BABYLON || (BABYLON = {}));
  10433. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10434. var BABYLON;
  10435. (function (BABYLON) {
  10436. var _DepthCullingState = /** @class */ (function () {
  10437. /**
  10438. * Initializes the state.
  10439. */
  10440. function _DepthCullingState() {
  10441. this._isDepthTestDirty = false;
  10442. this._isDepthMaskDirty = false;
  10443. this._isDepthFuncDirty = false;
  10444. this._isCullFaceDirty = false;
  10445. this._isCullDirty = false;
  10446. this._isZOffsetDirty = false;
  10447. this._isFrontFaceDirty = false;
  10448. this.reset();
  10449. }
  10450. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10451. get: function () {
  10452. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10453. },
  10454. enumerable: true,
  10455. configurable: true
  10456. });
  10457. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10458. get: function () {
  10459. return this._zOffset;
  10460. },
  10461. set: function (value) {
  10462. if (this._zOffset === value) {
  10463. return;
  10464. }
  10465. this._zOffset = value;
  10466. this._isZOffsetDirty = true;
  10467. },
  10468. enumerable: true,
  10469. configurable: true
  10470. });
  10471. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10472. get: function () {
  10473. return this._cullFace;
  10474. },
  10475. set: function (value) {
  10476. if (this._cullFace === value) {
  10477. return;
  10478. }
  10479. this._cullFace = value;
  10480. this._isCullFaceDirty = true;
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10486. get: function () {
  10487. return this._cull;
  10488. },
  10489. set: function (value) {
  10490. if (this._cull === value) {
  10491. return;
  10492. }
  10493. this._cull = value;
  10494. this._isCullDirty = true;
  10495. },
  10496. enumerable: true,
  10497. configurable: true
  10498. });
  10499. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10500. get: function () {
  10501. return this._depthFunc;
  10502. },
  10503. set: function (value) {
  10504. if (this._depthFunc === value) {
  10505. return;
  10506. }
  10507. this._depthFunc = value;
  10508. this._isDepthFuncDirty = true;
  10509. },
  10510. enumerable: true,
  10511. configurable: true
  10512. });
  10513. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10514. get: function () {
  10515. return this._depthMask;
  10516. },
  10517. set: function (value) {
  10518. if (this._depthMask === value) {
  10519. return;
  10520. }
  10521. this._depthMask = value;
  10522. this._isDepthMaskDirty = true;
  10523. },
  10524. enumerable: true,
  10525. configurable: true
  10526. });
  10527. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10528. get: function () {
  10529. return this._depthTest;
  10530. },
  10531. set: function (value) {
  10532. if (this._depthTest === value) {
  10533. return;
  10534. }
  10535. this._depthTest = value;
  10536. this._isDepthTestDirty = true;
  10537. },
  10538. enumerable: true,
  10539. configurable: true
  10540. });
  10541. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10542. get: function () {
  10543. return this._frontFace;
  10544. },
  10545. set: function (value) {
  10546. if (this._frontFace === value) {
  10547. return;
  10548. }
  10549. this._frontFace = value;
  10550. this._isFrontFaceDirty = true;
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. _DepthCullingState.prototype.reset = function () {
  10556. this._depthMask = true;
  10557. this._depthTest = true;
  10558. this._depthFunc = null;
  10559. this._cullFace = null;
  10560. this._cull = null;
  10561. this._zOffset = 0;
  10562. this._frontFace = null;
  10563. this._isDepthTestDirty = true;
  10564. this._isDepthMaskDirty = true;
  10565. this._isDepthFuncDirty = false;
  10566. this._isCullFaceDirty = false;
  10567. this._isCullDirty = false;
  10568. this._isZOffsetDirty = false;
  10569. this._isFrontFaceDirty = false;
  10570. };
  10571. _DepthCullingState.prototype.apply = function (gl) {
  10572. if (!this.isDirty) {
  10573. return;
  10574. }
  10575. // Cull
  10576. if (this._isCullDirty) {
  10577. if (this.cull) {
  10578. gl.enable(gl.CULL_FACE);
  10579. }
  10580. else {
  10581. gl.disable(gl.CULL_FACE);
  10582. }
  10583. this._isCullDirty = false;
  10584. }
  10585. // Cull face
  10586. if (this._isCullFaceDirty) {
  10587. gl.cullFace(this.cullFace);
  10588. this._isCullFaceDirty = false;
  10589. }
  10590. // Depth mask
  10591. if (this._isDepthMaskDirty) {
  10592. gl.depthMask(this.depthMask);
  10593. this._isDepthMaskDirty = false;
  10594. }
  10595. // Depth test
  10596. if (this._isDepthTestDirty) {
  10597. if (this.depthTest) {
  10598. gl.enable(gl.DEPTH_TEST);
  10599. }
  10600. else {
  10601. gl.disable(gl.DEPTH_TEST);
  10602. }
  10603. this._isDepthTestDirty = false;
  10604. }
  10605. // Depth func
  10606. if (this._isDepthFuncDirty) {
  10607. gl.depthFunc(this.depthFunc);
  10608. this._isDepthFuncDirty = false;
  10609. }
  10610. // zOffset
  10611. if (this._isZOffsetDirty) {
  10612. if (this.zOffset) {
  10613. gl.enable(gl.POLYGON_OFFSET_FILL);
  10614. gl.polygonOffset(this.zOffset, 0);
  10615. }
  10616. else {
  10617. gl.disable(gl.POLYGON_OFFSET_FILL);
  10618. }
  10619. this._isZOffsetDirty = false;
  10620. }
  10621. // Front face
  10622. if (this._isFrontFaceDirty) {
  10623. gl.frontFace(this.frontFace);
  10624. this._isFrontFaceDirty = false;
  10625. }
  10626. };
  10627. return _DepthCullingState;
  10628. }());
  10629. BABYLON._DepthCullingState = _DepthCullingState;
  10630. })(BABYLON || (BABYLON = {}));
  10631. //# sourceMappingURL=babylon.depthCullingState.js.map
  10632. var BABYLON;
  10633. (function (BABYLON) {
  10634. var _StencilState = /** @class */ (function () {
  10635. function _StencilState() {
  10636. this._isStencilTestDirty = false;
  10637. this._isStencilMaskDirty = false;
  10638. this._isStencilFuncDirty = false;
  10639. this._isStencilOpDirty = false;
  10640. this.reset();
  10641. }
  10642. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10643. get: function () {
  10644. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10650. get: function () {
  10651. return this._stencilFunc;
  10652. },
  10653. set: function (value) {
  10654. if (this._stencilFunc === value) {
  10655. return;
  10656. }
  10657. this._stencilFunc = value;
  10658. this._isStencilFuncDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10664. get: function () {
  10665. return this._stencilFuncRef;
  10666. },
  10667. set: function (value) {
  10668. if (this._stencilFuncRef === value) {
  10669. return;
  10670. }
  10671. this._stencilFuncRef = value;
  10672. this._isStencilFuncDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10678. get: function () {
  10679. return this._stencilFuncMask;
  10680. },
  10681. set: function (value) {
  10682. if (this._stencilFuncMask === value) {
  10683. return;
  10684. }
  10685. this._stencilFuncMask = value;
  10686. this._isStencilFuncDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10692. get: function () {
  10693. return this._stencilOpStencilFail;
  10694. },
  10695. set: function (value) {
  10696. if (this._stencilOpStencilFail === value) {
  10697. return;
  10698. }
  10699. this._stencilOpStencilFail = value;
  10700. this._isStencilOpDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10706. get: function () {
  10707. return this._stencilOpDepthFail;
  10708. },
  10709. set: function (value) {
  10710. if (this._stencilOpDepthFail === value) {
  10711. return;
  10712. }
  10713. this._stencilOpDepthFail = value;
  10714. this._isStencilOpDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10720. get: function () {
  10721. return this._stencilOpStencilDepthPass;
  10722. },
  10723. set: function (value) {
  10724. if (this._stencilOpStencilDepthPass === value) {
  10725. return;
  10726. }
  10727. this._stencilOpStencilDepthPass = value;
  10728. this._isStencilOpDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10734. get: function () {
  10735. return this._stencilMask;
  10736. },
  10737. set: function (value) {
  10738. if (this._stencilMask === value) {
  10739. return;
  10740. }
  10741. this._stencilMask = value;
  10742. this._isStencilMaskDirty = true;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10748. get: function () {
  10749. return this._stencilTest;
  10750. },
  10751. set: function (value) {
  10752. if (this._stencilTest === value) {
  10753. return;
  10754. }
  10755. this._stencilTest = value;
  10756. this._isStencilTestDirty = true;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. _StencilState.prototype.reset = function () {
  10762. this._stencilTest = false;
  10763. this._stencilMask = 0xFF;
  10764. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10765. this._stencilFuncRef = 1;
  10766. this._stencilFuncMask = 0xFF;
  10767. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10768. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10769. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10770. this._isStencilTestDirty = true;
  10771. this._isStencilMaskDirty = true;
  10772. this._isStencilFuncDirty = true;
  10773. this._isStencilOpDirty = true;
  10774. };
  10775. _StencilState.prototype.apply = function (gl) {
  10776. if (!this.isDirty) {
  10777. return;
  10778. }
  10779. // Stencil test
  10780. if (this._isStencilTestDirty) {
  10781. if (this.stencilTest) {
  10782. gl.enable(gl.STENCIL_TEST);
  10783. }
  10784. else {
  10785. gl.disable(gl.STENCIL_TEST);
  10786. }
  10787. this._isStencilTestDirty = false;
  10788. }
  10789. // Stencil mask
  10790. if (this._isStencilMaskDirty) {
  10791. gl.stencilMask(this.stencilMask);
  10792. this._isStencilMaskDirty = false;
  10793. }
  10794. // Stencil func
  10795. if (this._isStencilFuncDirty) {
  10796. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10797. this._isStencilFuncDirty = false;
  10798. }
  10799. // Stencil op
  10800. if (this._isStencilOpDirty) {
  10801. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10802. this._isStencilOpDirty = false;
  10803. }
  10804. };
  10805. return _StencilState;
  10806. }());
  10807. BABYLON._StencilState = _StencilState;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.stencilState.js.map
  10810. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10811. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10812. s = arguments[i];
  10813. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10814. t[p] = s[p];
  10815. }
  10816. return t;
  10817. };
  10818. var BABYLON;
  10819. (function (BABYLON) {
  10820. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10821. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10822. };
  10823. var compileRawShader = function (gl, source, type) {
  10824. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10825. gl.shaderSource(shader, source);
  10826. gl.compileShader(shader);
  10827. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10828. var log = gl.getShaderInfoLog(shader);
  10829. if (log) {
  10830. throw new Error(log);
  10831. }
  10832. }
  10833. if (!shader) {
  10834. throw new Error("Something went wrong while compile the shader.");
  10835. }
  10836. return shader;
  10837. };
  10838. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10839. var magFilter = gl.NEAREST;
  10840. var minFilter = gl.NEAREST;
  10841. switch (samplingMode) {
  10842. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10843. magFilter = gl.LINEAR;
  10844. if (generateMipMaps) {
  10845. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10846. }
  10847. else {
  10848. minFilter = gl.LINEAR;
  10849. }
  10850. break;
  10851. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10852. magFilter = gl.LINEAR;
  10853. if (generateMipMaps) {
  10854. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10855. }
  10856. else {
  10857. minFilter = gl.LINEAR;
  10858. }
  10859. break;
  10860. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10861. magFilter = gl.NEAREST;
  10862. if (generateMipMaps) {
  10863. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10864. }
  10865. else {
  10866. minFilter = gl.NEAREST;
  10867. }
  10868. break;
  10869. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10870. magFilter = gl.NEAREST;
  10871. if (generateMipMaps) {
  10872. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10873. }
  10874. else {
  10875. minFilter = gl.NEAREST;
  10876. }
  10877. break;
  10878. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10879. magFilter = gl.NEAREST;
  10880. if (generateMipMaps) {
  10881. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10882. }
  10883. else {
  10884. minFilter = gl.LINEAR;
  10885. }
  10886. break;
  10887. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10888. magFilter = gl.NEAREST;
  10889. if (generateMipMaps) {
  10890. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10891. }
  10892. else {
  10893. minFilter = gl.LINEAR;
  10894. }
  10895. break;
  10896. case BABYLON.Texture.NEAREST_LINEAR:
  10897. magFilter = gl.NEAREST;
  10898. minFilter = gl.LINEAR;
  10899. break;
  10900. case BABYLON.Texture.NEAREST_NEAREST:
  10901. magFilter = gl.NEAREST;
  10902. minFilter = gl.NEAREST;
  10903. break;
  10904. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10905. magFilter = gl.LINEAR;
  10906. if (generateMipMaps) {
  10907. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10908. }
  10909. else {
  10910. minFilter = gl.NEAREST;
  10911. }
  10912. break;
  10913. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10914. magFilter = gl.LINEAR;
  10915. if (generateMipMaps) {
  10916. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10917. }
  10918. else {
  10919. minFilter = gl.NEAREST;
  10920. }
  10921. break;
  10922. case BABYLON.Texture.LINEAR_LINEAR:
  10923. magFilter = gl.LINEAR;
  10924. minFilter = gl.LINEAR;
  10925. break;
  10926. case BABYLON.Texture.LINEAR_NEAREST:
  10927. magFilter = gl.LINEAR;
  10928. minFilter = gl.NEAREST;
  10929. break;
  10930. }
  10931. return {
  10932. min: minFilter,
  10933. mag: magFilter
  10934. };
  10935. };
  10936. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10937. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10938. var img;
  10939. var onload = function () {
  10940. loadedImages[index] = img;
  10941. loadedImages._internalCount++;
  10942. if (scene) {
  10943. scene._removePendingData(img);
  10944. }
  10945. if (loadedImages._internalCount === 6) {
  10946. onfinish(loadedImages);
  10947. }
  10948. };
  10949. var onerror = function (message, exception) {
  10950. if (scene) {
  10951. scene._removePendingData(img);
  10952. }
  10953. if (onErrorCallBack) {
  10954. onErrorCallBack(message, exception);
  10955. }
  10956. };
  10957. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10958. if (scene) {
  10959. scene._addPendingData(img);
  10960. }
  10961. };
  10962. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10963. if (onError === void 0) { onError = null; }
  10964. var loadedImages = [];
  10965. loadedImages._internalCount = 0;
  10966. for (var index = 0; index < 6; index++) {
  10967. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10968. }
  10969. };
  10970. var BufferPointer = /** @class */ (function () {
  10971. function BufferPointer() {
  10972. }
  10973. return BufferPointer;
  10974. }());
  10975. /**
  10976. * Interface for attribute information associated with buffer instanciation
  10977. */
  10978. var InstancingAttributeInfo = /** @class */ (function () {
  10979. function InstancingAttributeInfo() {
  10980. }
  10981. return InstancingAttributeInfo;
  10982. }());
  10983. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10984. /**
  10985. * Define options used to create a render target texture
  10986. */
  10987. var RenderTargetCreationOptions = /** @class */ (function () {
  10988. function RenderTargetCreationOptions() {
  10989. }
  10990. return RenderTargetCreationOptions;
  10991. }());
  10992. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10993. /**
  10994. * Define options used to create a depth texture
  10995. */
  10996. var DepthTextureCreationOptions = /** @class */ (function () {
  10997. function DepthTextureCreationOptions() {
  10998. }
  10999. return DepthTextureCreationOptions;
  11000. }());
  11001. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11002. /**
  11003. * Class used to describe the capabilities of the engine relatively to the current browser
  11004. */
  11005. var EngineCapabilities = /** @class */ (function () {
  11006. function EngineCapabilities() {
  11007. }
  11008. return EngineCapabilities;
  11009. }());
  11010. BABYLON.EngineCapabilities = EngineCapabilities;
  11011. /**
  11012. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11013. */
  11014. var Engine = /** @class */ (function () {
  11015. /**
  11016. * Creates a new engine
  11017. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11018. * @param antialias defines enable antialiasing (default: false)
  11019. * @param options defines further options to be sent to the getContext() function
  11020. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11021. */
  11022. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11023. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11024. var _this = this;
  11025. // Public members
  11026. /**
  11027. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11028. */
  11029. this.forcePOTTextures = false;
  11030. /**
  11031. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11032. */
  11033. this.isFullscreen = false;
  11034. /**
  11035. * Gets a boolean indicating if the pointer is currently locked
  11036. */
  11037. this.isPointerLock = false;
  11038. /**
  11039. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11040. */
  11041. this.cullBackFaces = true;
  11042. /**
  11043. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11044. */
  11045. this.renderEvenInBackground = true;
  11046. /**
  11047. * Gets or sets a boolean indicating that cache can be kept between frames
  11048. */
  11049. this.preventCacheWipeBetweenFrames = false;
  11050. /**
  11051. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11052. **/
  11053. this.enableOfflineSupport = false;
  11054. /**
  11055. * Gets the list of created scenes
  11056. */
  11057. this.scenes = new Array();
  11058. /**
  11059. * Gets the list of created postprocesses
  11060. */
  11061. this.postProcesses = new Array();
  11062. // Observables
  11063. /**
  11064. * Observable event triggered each time the rendering canvas is resized
  11065. */
  11066. this.onResizeObservable = new BABYLON.Observable();
  11067. /**
  11068. * Observable event triggered each time the canvas loses focus
  11069. */
  11070. this.onCanvasBlurObservable = new BABYLON.Observable();
  11071. /**
  11072. * Observable event triggered each time the canvas gains focus
  11073. */
  11074. this.onCanvasFocusObservable = new BABYLON.Observable();
  11075. /**
  11076. * Observable event triggered each time the canvas receives pointerout event
  11077. */
  11078. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11079. /**
  11080. * Observable event triggered before each texture is initialized
  11081. */
  11082. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11083. //WebVR
  11084. this._vrDisplay = undefined;
  11085. this._vrSupported = false;
  11086. this._vrExclusivePointerMode = false;
  11087. // Uniform buffers list
  11088. /**
  11089. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11090. */
  11091. this.disableUniformBuffers = false;
  11092. /** @ignore */
  11093. this._uniformBuffers = new Array();
  11094. // Observables
  11095. /**
  11096. * Observable raised when the engine begins a new frame
  11097. */
  11098. this.onBeginFrameObservable = new BABYLON.Observable();
  11099. /**
  11100. * Observable raised when the engine ends the current frame
  11101. */
  11102. this.onEndFrameObservable = new BABYLON.Observable();
  11103. /**
  11104. * Observable raised when the engine is about to compile a shader
  11105. */
  11106. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11107. /**
  11108. * Observable raised when the engine has jsut compiled a shader
  11109. */
  11110. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11111. this._windowIsBackground = false;
  11112. this._webGLVersion = 1.0;
  11113. /** @ignore */
  11114. this._badOS = false;
  11115. /** @ignore */
  11116. this._badDesktopOS = false;
  11117. /**
  11118. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11119. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11120. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11121. */
  11122. this.disableTextureBindingOptimization = false;
  11123. /**
  11124. * Observable signaled when VR display mode changes
  11125. */
  11126. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11127. /**
  11128. * Observable signaled when VR request present is complete
  11129. */
  11130. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11131. /**
  11132. * Observable signaled when VR request present starts
  11133. */
  11134. this.onVRRequestPresentStart = new BABYLON.Observable();
  11135. this._colorWrite = true;
  11136. /** @ignore */
  11137. this._drawCalls = new BABYLON.PerfCounter();
  11138. /** @ignore */
  11139. this._textureCollisions = new BABYLON.PerfCounter();
  11140. this._renderingQueueLaunched = false;
  11141. this._activeRenderLoops = new Array();
  11142. // Deterministic lockstepMaxSteps
  11143. this._deterministicLockstep = false;
  11144. this._lockstepMaxSteps = 4;
  11145. // Lost context
  11146. /**
  11147. * Observable signaled when a context lost event is raised
  11148. */
  11149. this.onContextLostObservable = new BABYLON.Observable();
  11150. /**
  11151. * Observable signaled when a context restored event is raised
  11152. */
  11153. this.onContextRestoredObservable = new BABYLON.Observable();
  11154. this._contextWasLost = false;
  11155. this._doNotHandleContextLost = false;
  11156. // FPS
  11157. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11158. this._fps = 60;
  11159. this._deltaTime = 0;
  11160. /**
  11161. * Turn this value on if you want to pause FPS computation when in background
  11162. */
  11163. this.disablePerformanceMonitorInBackground = false;
  11164. // States
  11165. /** @ignore */
  11166. this._depthCullingState = new BABYLON._DepthCullingState();
  11167. /** @ignore */
  11168. this._stencilState = new BABYLON._StencilState();
  11169. /** @ignore */
  11170. this._alphaState = new BABYLON._AlphaState();
  11171. /** @ignore */
  11172. this._alphaMode = Engine.ALPHA_DISABLE;
  11173. // Cache
  11174. this._internalTexturesCache = new Array();
  11175. /** @ignore */
  11176. this._activeChannel = 0;
  11177. this._currentTextureChannel = -1;
  11178. /** @ignore */
  11179. this._boundTexturesCache = {};
  11180. this._compiledEffects = {};
  11181. this._vertexAttribArraysEnabled = [];
  11182. this._uintIndicesCurrentlySet = false;
  11183. this._currentBoundBuffer = new Array();
  11184. this._currentBufferPointers = new Array();
  11185. this._currentInstanceLocations = new Array();
  11186. this._currentInstanceBuffers = new Array();
  11187. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11188. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11189. this._vaoRecordInProgress = false;
  11190. this._mustWipeVertexAttributes = false;
  11191. this._nextFreeTextureSlots = new Array();
  11192. this._maxSimultaneousTextures = 0;
  11193. this._activeRequests = new Array();
  11194. // Hardware supported Compressed Textures
  11195. this._texturesSupported = new Array();
  11196. this._onVRFullScreenTriggered = function () {
  11197. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11198. //get the old size before we change
  11199. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11200. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11201. //get the width and height, change the render size
  11202. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11203. _this.setHardwareScalingLevel(1);
  11204. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11205. }
  11206. else {
  11207. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11208. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11209. }
  11210. };
  11211. this._boundUniforms = {};
  11212. // Register promises
  11213. BABYLON.PromisePolyfill.Apply();
  11214. var canvas = null;
  11215. Engine.Instances.push(this);
  11216. if (!canvasOrContext) {
  11217. return;
  11218. }
  11219. options = options || {};
  11220. if (canvasOrContext.getContext) {
  11221. canvas = canvasOrContext;
  11222. this._renderingCanvas = canvas;
  11223. if (antialias != null) {
  11224. options.antialias = antialias;
  11225. }
  11226. if (options.deterministicLockstep === undefined) {
  11227. options.deterministicLockstep = false;
  11228. }
  11229. if (options.lockstepMaxSteps === undefined) {
  11230. options.lockstepMaxSteps = 4;
  11231. }
  11232. if (options.preserveDrawingBuffer === undefined) {
  11233. options.preserveDrawingBuffer = false;
  11234. }
  11235. if (options.audioEngine === undefined) {
  11236. options.audioEngine = true;
  11237. }
  11238. if (options.stencil === undefined) {
  11239. options.stencil = true;
  11240. }
  11241. this._deterministicLockstep = options.deterministicLockstep;
  11242. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11243. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11244. // Exceptions
  11245. if (navigator && navigator.userAgent) {
  11246. var ua = navigator.userAgent;
  11247. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11248. var exception = _a[_i];
  11249. var key = exception.key;
  11250. var targets = exception.targets;
  11251. if (ua.indexOf(key) > -1) {
  11252. if (exception.capture && exception.captureConstraint) {
  11253. var capture = exception.capture;
  11254. var constraint = exception.captureConstraint;
  11255. var regex = new RegExp(capture);
  11256. var matches = regex.exec(ua);
  11257. if (matches && matches.length > 0) {
  11258. var capturedValue = parseInt(matches[matches.length - 1]);
  11259. if (capturedValue >= constraint) {
  11260. continue;
  11261. }
  11262. }
  11263. }
  11264. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11265. var target = targets_1[_b];
  11266. switch (target) {
  11267. case "uniformBuffer":
  11268. this.disableUniformBuffers = true;
  11269. break;
  11270. case "textureBindingOptimization":
  11271. this.disableTextureBindingOptimization = true;
  11272. break;
  11273. }
  11274. }
  11275. }
  11276. }
  11277. }
  11278. // GL
  11279. if (!options.disableWebGL2Support) {
  11280. try {
  11281. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11282. if (this._gl) {
  11283. this._webGLVersion = 2.0;
  11284. }
  11285. }
  11286. catch (e) {
  11287. // Do nothing
  11288. }
  11289. }
  11290. if (!this._gl) {
  11291. if (!canvas) {
  11292. throw new Error("The provided canvas is null or undefined.");
  11293. }
  11294. try {
  11295. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11296. }
  11297. catch (e) {
  11298. throw new Error("WebGL not supported");
  11299. }
  11300. }
  11301. if (!this._gl) {
  11302. throw new Error("WebGL not supported");
  11303. }
  11304. this._onCanvasFocus = function () {
  11305. _this.onCanvasFocusObservable.notifyObservers(_this);
  11306. };
  11307. this._onCanvasBlur = function () {
  11308. _this.onCanvasBlurObservable.notifyObservers(_this);
  11309. };
  11310. canvas.addEventListener("focus", this._onCanvasFocus);
  11311. canvas.addEventListener("blur", this._onCanvasBlur);
  11312. this._onBlur = function () {
  11313. if (_this.disablePerformanceMonitorInBackground) {
  11314. _this._performanceMonitor.disable();
  11315. }
  11316. _this._windowIsBackground = true;
  11317. };
  11318. this._onFocus = function () {
  11319. if (_this.disablePerformanceMonitorInBackground) {
  11320. _this._performanceMonitor.enable();
  11321. }
  11322. _this._windowIsBackground = false;
  11323. };
  11324. this._onCanvasPointerOut = function (ev) {
  11325. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11326. };
  11327. window.addEventListener("blur", this._onBlur);
  11328. window.addEventListener("focus", this._onFocus);
  11329. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11330. // Context lost
  11331. if (!this._doNotHandleContextLost) {
  11332. this._onContextLost = function (evt) {
  11333. evt.preventDefault();
  11334. _this._contextWasLost = true;
  11335. BABYLON.Tools.Warn("WebGL context lost.");
  11336. _this.onContextLostObservable.notifyObservers(_this);
  11337. };
  11338. this._onContextRestored = function (evt) {
  11339. // Adding a timeout to avoid race condition at browser level
  11340. setTimeout(function () {
  11341. // Rebuild gl context
  11342. _this._initGLContext();
  11343. // Rebuild effects
  11344. _this._rebuildEffects();
  11345. // Rebuild textures
  11346. _this._rebuildInternalTextures();
  11347. // Rebuild buffers
  11348. _this._rebuildBuffers();
  11349. // Cache
  11350. _this.wipeCaches(true);
  11351. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11352. _this.onContextRestoredObservable.notifyObservers(_this);
  11353. _this._contextWasLost = false;
  11354. }, 0);
  11355. };
  11356. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11357. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11358. }
  11359. }
  11360. else {
  11361. this._gl = canvasOrContext;
  11362. this._renderingCanvas = this._gl.canvas;
  11363. if (this._gl.renderbufferStorageMultisample) {
  11364. this._webGLVersion = 2.0;
  11365. }
  11366. options.stencil = this._gl.getContextAttributes().stencil;
  11367. }
  11368. // Viewport
  11369. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11370. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11371. this.resize();
  11372. this._isStencilEnable = options.stencil ? true : false;
  11373. this._initGLContext();
  11374. if (canvas) {
  11375. // Fullscreen
  11376. this._onFullscreenChange = function () {
  11377. if (document.fullscreen !== undefined) {
  11378. _this.isFullscreen = document.fullscreen;
  11379. }
  11380. else if (document.mozFullScreen !== undefined) {
  11381. _this.isFullscreen = document.mozFullScreen;
  11382. }
  11383. else if (document.webkitIsFullScreen !== undefined) {
  11384. _this.isFullscreen = document.webkitIsFullScreen;
  11385. }
  11386. else if (document.msIsFullScreen !== undefined) {
  11387. _this.isFullscreen = document.msIsFullScreen;
  11388. }
  11389. // Pointer lock
  11390. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11391. canvas.requestPointerLock = canvas.requestPointerLock ||
  11392. canvas.msRequestPointerLock ||
  11393. canvas.mozRequestPointerLock ||
  11394. canvas.webkitRequestPointerLock;
  11395. if (canvas.requestPointerLock) {
  11396. canvas.requestPointerLock();
  11397. }
  11398. }
  11399. };
  11400. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11401. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11402. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11403. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11404. // Pointer lock
  11405. this._onPointerLockChange = function () {
  11406. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11407. document.webkitPointerLockElement === canvas ||
  11408. document.msPointerLockElement === canvas ||
  11409. document.pointerLockElement === canvas);
  11410. };
  11411. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11412. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11413. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11414. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11415. this._onVRDisplayPointerRestricted = function () {
  11416. if (canvas) {
  11417. canvas.requestPointerLock();
  11418. }
  11419. };
  11420. this._onVRDisplayPointerUnrestricted = function () {
  11421. document.exitPointerLock();
  11422. };
  11423. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11424. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11425. }
  11426. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11427. Engine.audioEngine = new BABYLON.AudioEngine();
  11428. }
  11429. // Prepare buffer pointers
  11430. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11431. this._currentBufferPointers[i] = new BufferPointer();
  11432. }
  11433. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11434. // Load WebVR Devices
  11435. if (options.autoEnableWebVR) {
  11436. this.initWebVR();
  11437. }
  11438. // Detect if we are running on a faulty buggy OS.
  11439. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11440. // Detect if we are running on a faulty buggy desktop OS.
  11441. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11442. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11443. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11444. }
  11445. Object.defineProperty(Engine, "LastCreatedEngine", {
  11446. /**
  11447. * Gets the latest created engine
  11448. */
  11449. get: function () {
  11450. if (Engine.Instances.length === 0) {
  11451. return null;
  11452. }
  11453. return Engine.Instances[Engine.Instances.length - 1];
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Engine, "LastCreatedScene", {
  11459. /**
  11460. * Gets the latest created scene
  11461. */
  11462. get: function () {
  11463. var lastCreatedEngine = Engine.LastCreatedEngine;
  11464. if (!lastCreatedEngine) {
  11465. return null;
  11466. }
  11467. if (lastCreatedEngine.scenes.length === 0) {
  11468. return null;
  11469. }
  11470. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. /**
  11476. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11477. * @param flag defines which part of the materials must be marked as dirty
  11478. * @param predicate defines a predicate used to filter which materials should be affected
  11479. */
  11480. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11481. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11482. var engine = Engine.Instances[engineIndex];
  11483. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11484. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11485. }
  11486. }
  11487. };
  11488. Object.defineProperty(Engine, "NEVER", {
  11489. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11490. get: function () {
  11491. return Engine._NEVER;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(Engine, "ALWAYS", {
  11497. /** 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 */
  11498. get: function () {
  11499. return Engine._ALWAYS;
  11500. },
  11501. enumerable: true,
  11502. configurable: true
  11503. });
  11504. Object.defineProperty(Engine, "LESS", {
  11505. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11506. get: function () {
  11507. return Engine._LESS;
  11508. },
  11509. enumerable: true,
  11510. configurable: true
  11511. });
  11512. Object.defineProperty(Engine, "EQUAL", {
  11513. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11514. get: function () {
  11515. return Engine._EQUAL;
  11516. },
  11517. enumerable: true,
  11518. configurable: true
  11519. });
  11520. Object.defineProperty(Engine, "LEQUAL", {
  11521. /** 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 */
  11522. get: function () {
  11523. return Engine._LEQUAL;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(Engine, "GREATER", {
  11529. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11530. get: function () {
  11531. return Engine._GREATER;
  11532. },
  11533. enumerable: true,
  11534. configurable: true
  11535. });
  11536. Object.defineProperty(Engine, "GEQUAL", {
  11537. /** 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 */
  11538. get: function () {
  11539. return Engine._GEQUAL;
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(Engine, "NOTEQUAL", {
  11545. /** 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 */
  11546. get: function () {
  11547. return Engine._NOTEQUAL;
  11548. },
  11549. enumerable: true,
  11550. configurable: true
  11551. });
  11552. Object.defineProperty(Engine, "KEEP", {
  11553. /** Passed to stencilOperation to specify that stencil value must be kept */
  11554. get: function () {
  11555. return Engine._KEEP;
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. Object.defineProperty(Engine, "REPLACE", {
  11561. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11562. get: function () {
  11563. return Engine._REPLACE;
  11564. },
  11565. enumerable: true,
  11566. configurable: true
  11567. });
  11568. Object.defineProperty(Engine, "INCR", {
  11569. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11570. get: function () {
  11571. return Engine._INCR;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(Engine, "DECR", {
  11577. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11578. get: function () {
  11579. return Engine._DECR;
  11580. },
  11581. enumerable: true,
  11582. configurable: true
  11583. });
  11584. Object.defineProperty(Engine, "INVERT", {
  11585. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11586. get: function () {
  11587. return Engine._INVERT;
  11588. },
  11589. enumerable: true,
  11590. configurable: true
  11591. });
  11592. Object.defineProperty(Engine, "INCR_WRAP", {
  11593. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11594. get: function () {
  11595. return Engine._INCR_WRAP;
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(Engine, "DECR_WRAP", {
  11601. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11602. get: function () {
  11603. return Engine._DECR_WRAP;
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11609. // Alpha
  11610. /** Defines that alpha blending is disabled */
  11611. get: function () {
  11612. return Engine._ALPHA_DISABLE;
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11618. /** Defines that alpha blending to SRC + DEST */
  11619. get: function () {
  11620. return Engine._ALPHA_ONEONE;
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. Object.defineProperty(Engine, "ALPHA_ADD", {
  11626. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11627. get: function () {
  11628. return Engine._ALPHA_ADD;
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11634. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11635. get: function () {
  11636. return Engine._ALPHA_COMBINE;
  11637. },
  11638. enumerable: true,
  11639. configurable: true
  11640. });
  11641. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11642. /** Defines that alpha blending to DEST - SRC * DEST */
  11643. get: function () {
  11644. return Engine._ALPHA_SUBTRACT;
  11645. },
  11646. enumerable: true,
  11647. configurable: true
  11648. });
  11649. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11650. /** Defines that alpha blending to SRC * DEST */
  11651. get: function () {
  11652. return Engine._ALPHA_MULTIPLY;
  11653. },
  11654. enumerable: true,
  11655. configurable: true
  11656. });
  11657. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11658. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11659. get: function () {
  11660. return Engine._ALPHA_MAXIMIZED;
  11661. },
  11662. enumerable: true,
  11663. configurable: true
  11664. });
  11665. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11666. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11667. get: function () {
  11668. return Engine._ALPHA_PREMULTIPLIED;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11674. /**
  11675. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11676. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11677. */
  11678. get: function () {
  11679. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11685. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11686. get: function () {
  11687. return Engine._ALPHA_INTERPOLATE;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11693. /**
  11694. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11695. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11696. */
  11697. get: function () {
  11698. return Engine._ALPHA_SCREENMODE;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11704. // Delays
  11705. /** Defines that the ressource is not delayed*/
  11706. get: function () {
  11707. return Engine._DELAYLOADSTATE_NONE;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11713. /** Defines that the ressource was successfully delay loaded */
  11714. get: function () {
  11715. return Engine._DELAYLOADSTATE_LOADED;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11721. /** Defines that the ressource is currently delay loading */
  11722. get: function () {
  11723. return Engine._DELAYLOADSTATE_LOADING;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11729. /** Defines that the ressource is delayed and has not started loading */
  11730. get: function () {
  11731. return Engine._DELAYLOADSTATE_NOTLOADED;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11737. /** ALPHA */
  11738. get: function () {
  11739. return Engine._TEXTUREFORMAT_ALPHA;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11745. /** LUMINANCE */
  11746. get: function () {
  11747. return Engine._TEXTUREFORMAT_LUMINANCE;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11753. /**
  11754. * R32F
  11755. */
  11756. get: function () {
  11757. return Engine._TEXTUREFORMAT_R32F;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11763. /**
  11764. * RG32F
  11765. */
  11766. get: function () {
  11767. return Engine._TEXTUREFORMAT_RG32F;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11773. /**
  11774. * RGB32F
  11775. */
  11776. get: function () {
  11777. return Engine._TEXTUREFORMAT_RGB32F;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11783. /**
  11784. * RGBA32F
  11785. */
  11786. get: function () {
  11787. return Engine._TEXTUREFORMAT_RGBA32F;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11793. /** LUMINANCE_ALPHA */
  11794. get: function () {
  11795. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11801. /** RGB */
  11802. get: function () {
  11803. return Engine._TEXTUREFORMAT_RGB;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11809. /** RGBA */
  11810. get: function () {
  11811. return Engine._TEXTUREFORMAT_RGBA;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11817. /** UNSIGNED_INT */
  11818. get: function () {
  11819. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11825. /** FLOAT */
  11826. get: function () {
  11827. return Engine._TEXTURETYPE_FLOAT;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11833. /** HALF_FLOAT */
  11834. get: function () {
  11835. return Engine._TEXTURETYPE_HALF_FLOAT;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11841. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11842. get: function () {
  11843. return Engine._SCALEMODE_FLOOR;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11849. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11850. get: function () {
  11851. return Engine._SCALEMODE_NEAREST;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11857. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11858. get: function () {
  11859. return Engine._SCALEMODE_CEILING;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "Version", {
  11865. /**
  11866. * Returns the current version of the framework
  11867. */
  11868. get: function () {
  11869. return "3.2.0-beta.4";
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11875. /**
  11876. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11877. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11878. */
  11879. get: function () {
  11880. return this._vrExclusivePointerMode;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11886. /**
  11887. * Gets a boolean indicating that the engine supports uniform buffers
  11888. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11889. */
  11890. get: function () {
  11891. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11897. /**
  11898. * Gets a boolean indicating that only power of 2 textures are supported
  11899. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11900. */
  11901. get: function () {
  11902. return this._webGLVersion < 2 || this.forcePOTTextures;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11908. /**
  11909. * Gets the performance monitor attached to this engine
  11910. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11911. */
  11912. get: function () {
  11913. return this._performanceMonitor;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11919. /**
  11920. * Gets the list of texture formats supported
  11921. */
  11922. get: function () {
  11923. return this._texturesSupported;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11929. /**
  11930. * Gets the list of texture formats in use
  11931. */
  11932. get: function () {
  11933. return this._textureFormatInUse;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine.prototype, "currentViewport", {
  11939. /**
  11940. * Gets the current viewport
  11941. */
  11942. get: function () {
  11943. return this._cachedViewport;
  11944. },
  11945. enumerable: true,
  11946. configurable: true
  11947. });
  11948. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11949. /**
  11950. * Gets the default empty texture
  11951. */
  11952. get: function () {
  11953. if (!this._emptyTexture) {
  11954. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11955. }
  11956. return this._emptyTexture;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11962. /**
  11963. * Gets the default empty 3D texture
  11964. */
  11965. get: function () {
  11966. if (!this._emptyTexture3D) {
  11967. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11968. }
  11969. return this._emptyTexture3D;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11975. /**
  11976. * Gets the default empty cube texture
  11977. */
  11978. get: function () {
  11979. if (!this._emptyCubeTexture) {
  11980. var faceData = new Uint8Array(4);
  11981. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11982. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11983. }
  11984. return this._emptyCubeTexture;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Engine.prototype._rebuildInternalTextures = function () {
  11990. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11991. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11992. var internalTexture = currentState_1[_i];
  11993. internalTexture._rebuild();
  11994. }
  11995. };
  11996. Engine.prototype._rebuildEffects = function () {
  11997. for (var key in this._compiledEffects) {
  11998. var effect = this._compiledEffects[key];
  11999. effect._prepareEffect();
  12000. }
  12001. BABYLON.Effect.ResetCache();
  12002. };
  12003. Engine.prototype._rebuildBuffers = function () {
  12004. // Index / Vertex
  12005. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12006. var scene = _a[_i];
  12007. scene.resetCachedMaterial();
  12008. scene._rebuildGeometries();
  12009. scene._rebuildTextures();
  12010. }
  12011. // Uniforms
  12012. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12013. var uniformBuffer = _c[_b];
  12014. uniformBuffer._rebuild();
  12015. }
  12016. };
  12017. Engine.prototype._initGLContext = function () {
  12018. // Caps
  12019. this._caps = new EngineCapabilities();
  12020. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12021. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12022. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12023. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12024. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12025. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12026. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12027. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12028. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12029. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12030. // Infos
  12031. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12032. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12033. if (rendererInfo != null) {
  12034. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12035. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12036. }
  12037. if (!this._glVendor) {
  12038. this._glVendor = "Unknown vendor";
  12039. }
  12040. if (!this._glRenderer) {
  12041. this._glRenderer = "Unknown renderer";
  12042. }
  12043. // Constants
  12044. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12045. if (this._gl.RGBA16F !== 0x881A) {
  12046. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12047. }
  12048. if (this._gl.RGBA32F !== 0x8814) {
  12049. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12050. }
  12051. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12052. this._gl.DEPTH24_STENCIL8 = 35056;
  12053. }
  12054. // Extensions
  12055. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12056. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12057. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12058. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12059. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12060. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12061. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12062. 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');
  12063. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12064. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12065. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12066. this._caps.highPrecisionShaderSupported = true;
  12067. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12068. if (this._caps.timerQuery) {
  12069. if (this._webGLVersion === 1) {
  12070. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12071. }
  12072. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12073. }
  12074. // Checks if some of the format renders first to allow the use of webgl inspector.
  12075. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12076. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12077. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12078. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12079. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12080. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12081. if (this._webGLVersion > 1) {
  12082. this._gl.HALF_FLOAT_OES = 0x140B;
  12083. }
  12084. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12085. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12086. // Draw buffers
  12087. if (this._webGLVersion > 1) {
  12088. this._caps.drawBuffersExtension = true;
  12089. }
  12090. else {
  12091. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12092. if (drawBuffersExtension !== null) {
  12093. this._caps.drawBuffersExtension = true;
  12094. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12095. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12096. for (var i = 0; i < 16; i++) {
  12097. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12098. }
  12099. }
  12100. else {
  12101. this._caps.drawBuffersExtension = false;
  12102. }
  12103. }
  12104. // Depth Texture
  12105. if (this._webGLVersion > 1) {
  12106. this._caps.depthTextureExtension = true;
  12107. }
  12108. else {
  12109. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12110. if (depthTextureExtension != null) {
  12111. this._caps.depthTextureExtension = true;
  12112. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12113. }
  12114. }
  12115. // Vertex array object
  12116. if (this._webGLVersion > 1) {
  12117. this._caps.vertexArrayObject = true;
  12118. }
  12119. else {
  12120. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12121. if (vertexArrayObjectExtension != null) {
  12122. this._caps.vertexArrayObject = true;
  12123. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12124. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12125. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12126. }
  12127. else {
  12128. this._caps.vertexArrayObject = false;
  12129. }
  12130. }
  12131. // Instances count
  12132. if (this._webGLVersion > 1) {
  12133. this._caps.instancedArrays = true;
  12134. }
  12135. else {
  12136. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12137. if (instanceExtension != null) {
  12138. this._caps.instancedArrays = true;
  12139. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12140. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12141. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12142. }
  12143. else {
  12144. this._caps.instancedArrays = false;
  12145. }
  12146. }
  12147. // Intelligently add supported compressed formats in order to check for.
  12148. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12149. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12150. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12151. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12152. if (this._caps.astc)
  12153. this.texturesSupported.push('-astc.ktx');
  12154. if (this._caps.s3tc)
  12155. this.texturesSupported.push('-dxt.ktx');
  12156. if (this._caps.pvrtc)
  12157. this.texturesSupported.push('-pvrtc.ktx');
  12158. if (this._caps.etc2)
  12159. this.texturesSupported.push('-etc2.ktx');
  12160. if (this._caps.etc1)
  12161. this.texturesSupported.push('-etc1.ktx');
  12162. if (this._gl.getShaderPrecisionFormat) {
  12163. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12164. if (highp) {
  12165. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12166. }
  12167. }
  12168. // Depth buffer
  12169. this.setDepthBuffer(true);
  12170. this.setDepthFunctionToLessOrEqual();
  12171. this.setDepthWrite(true);
  12172. // Texture maps
  12173. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12174. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12175. this._nextFreeTextureSlots.push(slot);
  12176. }
  12177. };
  12178. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12179. /**
  12180. * Gets version of the current webGL context
  12181. */
  12182. get: function () {
  12183. return this._webGLVersion;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12189. /**
  12190. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12191. */
  12192. get: function () {
  12193. return this._isStencilEnable;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Engine.prototype._prepareWorkingCanvas = function () {
  12199. if (this._workingCanvas) {
  12200. return;
  12201. }
  12202. this._workingCanvas = document.createElement("canvas");
  12203. var context = this._workingCanvas.getContext("2d");
  12204. if (context) {
  12205. this._workingContext = context;
  12206. }
  12207. };
  12208. /**
  12209. * Reset the texture cache to empty state
  12210. */
  12211. Engine.prototype.resetTextureCache = function () {
  12212. for (var key in this._boundTexturesCache) {
  12213. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12214. continue;
  12215. }
  12216. var boundTexture = this._boundTexturesCache[key];
  12217. if (boundTexture) {
  12218. this._removeDesignatedSlot(boundTexture);
  12219. }
  12220. this._boundTexturesCache[key] = null;
  12221. }
  12222. if (!this.disableTextureBindingOptimization) {
  12223. this._nextFreeTextureSlots = [];
  12224. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12225. this._nextFreeTextureSlots.push(slot);
  12226. }
  12227. }
  12228. this._currentTextureChannel = -1;
  12229. };
  12230. /**
  12231. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12232. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12233. * @returns true if engine is in deterministic lock step mode
  12234. */
  12235. Engine.prototype.isDeterministicLockStep = function () {
  12236. return this._deterministicLockstep;
  12237. };
  12238. /**
  12239. * Gets the max steps when engine is running in deterministic lock step
  12240. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12241. * @returns the max steps
  12242. */
  12243. Engine.prototype.getLockstepMaxSteps = function () {
  12244. return this._lockstepMaxSteps;
  12245. };
  12246. /**
  12247. * Gets an object containing information about the current webGL context
  12248. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12249. */
  12250. Engine.prototype.getGlInfo = function () {
  12251. return {
  12252. vendor: this._glVendor,
  12253. renderer: this._glRenderer,
  12254. version: this._glVersion
  12255. };
  12256. };
  12257. /**
  12258. * Gets current aspect ratio
  12259. * @param camera defines the camera to use to get the aspect ratio
  12260. * @param useScreen defines if screen size must be used (or the current render target if any)
  12261. * @returns a number defining the aspect ratio
  12262. */
  12263. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12264. if (useScreen === void 0) { useScreen = false; }
  12265. var viewport = camera.viewport;
  12266. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12267. };
  12268. /**
  12269. * Gets the current render width
  12270. * @param useScreen defines if screen size must be used (or the current render target if any)
  12271. * @returns a number defining the current render width
  12272. */
  12273. Engine.prototype.getRenderWidth = function (useScreen) {
  12274. if (useScreen === void 0) { useScreen = false; }
  12275. if (!useScreen && this._currentRenderTarget) {
  12276. return this._currentRenderTarget.width;
  12277. }
  12278. return this._gl.drawingBufferWidth;
  12279. };
  12280. /**
  12281. * Gets the current render height
  12282. * @param useScreen defines if screen size must be used (or the current render target if any)
  12283. * @returns a number defining the current render height
  12284. */
  12285. Engine.prototype.getRenderHeight = function (useScreen) {
  12286. if (useScreen === void 0) { useScreen = false; }
  12287. if (!useScreen && this._currentRenderTarget) {
  12288. return this._currentRenderTarget.height;
  12289. }
  12290. return this._gl.drawingBufferHeight;
  12291. };
  12292. /**
  12293. * Gets the HTML canvas attached with the current webGL context
  12294. * @returns a HTML canvas
  12295. */
  12296. Engine.prototype.getRenderingCanvas = function () {
  12297. return this._renderingCanvas;
  12298. };
  12299. /**
  12300. * Gets the client rect of the HTML canvas attached with the current webGL context
  12301. * @returns a client rectanglee
  12302. */
  12303. Engine.prototype.getRenderingCanvasClientRect = function () {
  12304. if (!this._renderingCanvas) {
  12305. return null;
  12306. }
  12307. return this._renderingCanvas.getBoundingClientRect();
  12308. };
  12309. /**
  12310. * Defines the hardware scaling level.
  12311. * By default the hardware scaling level is computed from the window device ratio.
  12312. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12313. * @param level defines the level to use
  12314. */
  12315. Engine.prototype.setHardwareScalingLevel = function (level) {
  12316. this._hardwareScalingLevel = level;
  12317. this.resize();
  12318. };
  12319. /**
  12320. * Gets the current hardware scaling level.
  12321. * By default the hardware scaling level is computed from the window device ratio.
  12322. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12323. * @returns a number indicating the current hardware scaling level
  12324. */
  12325. Engine.prototype.getHardwareScalingLevel = function () {
  12326. return this._hardwareScalingLevel;
  12327. };
  12328. /**
  12329. * Gets the list of loaded textures
  12330. * @returns an array containing all loaded textures
  12331. */
  12332. Engine.prototype.getLoadedTexturesCache = function () {
  12333. return this._internalTexturesCache;
  12334. };
  12335. /**
  12336. * Gets the object containing all engine capabilities
  12337. * @returns the EngineCapabilities object
  12338. */
  12339. Engine.prototype.getCaps = function () {
  12340. return this._caps;
  12341. };
  12342. Object.defineProperty(Engine.prototype, "drawCalls", {
  12343. /** @ignore */
  12344. get: function () {
  12345. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12346. return 0;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12352. /** @ignore */
  12353. get: function () {
  12354. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12355. return null;
  12356. },
  12357. enumerable: true,
  12358. configurable: true
  12359. });
  12360. /**
  12361. * Gets the current depth function
  12362. * @returns a number defining the depth function
  12363. */
  12364. Engine.prototype.getDepthFunction = function () {
  12365. return this._depthCullingState.depthFunc;
  12366. };
  12367. /**
  12368. * Sets the current depth function
  12369. * @param depthFunc defines the function to use
  12370. */
  12371. Engine.prototype.setDepthFunction = function (depthFunc) {
  12372. this._depthCullingState.depthFunc = depthFunc;
  12373. };
  12374. /**
  12375. * Sets the current depth function to GREATER
  12376. */
  12377. Engine.prototype.setDepthFunctionToGreater = function () {
  12378. this._depthCullingState.depthFunc = this._gl.GREATER;
  12379. };
  12380. /**
  12381. * Sets the current depth function to GEQUAL
  12382. */
  12383. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12384. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12385. };
  12386. /**
  12387. * Sets the current depth function to LESS
  12388. */
  12389. Engine.prototype.setDepthFunctionToLess = function () {
  12390. this._depthCullingState.depthFunc = this._gl.LESS;
  12391. };
  12392. /**
  12393. * Sets the current depth function to LEQUAL
  12394. */
  12395. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12396. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12397. };
  12398. /**
  12399. * Gets a boolean indicating if stencil buffer is enabled
  12400. * @returns the current stencil buffer state
  12401. */
  12402. Engine.prototype.getStencilBuffer = function () {
  12403. return this._stencilState.stencilTest;
  12404. };
  12405. /**
  12406. * Enable or disable the stencil buffer
  12407. * @param enable defines if the stencil buffer must be enabled or disabled
  12408. */
  12409. Engine.prototype.setStencilBuffer = function (enable) {
  12410. this._stencilState.stencilTest = enable;
  12411. };
  12412. /**
  12413. * Gets the current stencil mask
  12414. * @returns a number defining the new stencil mask to use
  12415. */
  12416. Engine.prototype.getStencilMask = function () {
  12417. return this._stencilState.stencilMask;
  12418. };
  12419. /**
  12420. * Sets the current stencil mask
  12421. * @param mask defines the new stencil mask to use
  12422. */
  12423. Engine.prototype.setStencilMask = function (mask) {
  12424. this._stencilState.stencilMask = mask;
  12425. };
  12426. /**
  12427. * Gets the current stencil function
  12428. * @returns a number defining the stencil function to use
  12429. */
  12430. Engine.prototype.getStencilFunction = function () {
  12431. return this._stencilState.stencilFunc;
  12432. };
  12433. /**
  12434. * Gets the current stencil reference value
  12435. * @returns a number defining the stencil reference value to use
  12436. */
  12437. Engine.prototype.getStencilFunctionReference = function () {
  12438. return this._stencilState.stencilFuncRef;
  12439. };
  12440. /**
  12441. * Gets the current stencil mask
  12442. * @returns a number defining the stencil mask to use
  12443. */
  12444. Engine.prototype.getStencilFunctionMask = function () {
  12445. return this._stencilState.stencilFuncMask;
  12446. };
  12447. /**
  12448. * Sets the current stencil function
  12449. * @param stencilFunc defines the new stencil function to use
  12450. */
  12451. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12452. this._stencilState.stencilFunc = stencilFunc;
  12453. };
  12454. /**
  12455. * Sets the current stencil reference
  12456. * @param reference defines the new stencil reference to use
  12457. */
  12458. Engine.prototype.setStencilFunctionReference = function (reference) {
  12459. this._stencilState.stencilFuncRef = reference;
  12460. };
  12461. /**
  12462. * Sets the current stencil mask
  12463. * @param mask defines the new stencil mask to use
  12464. */
  12465. Engine.prototype.setStencilFunctionMask = function (mask) {
  12466. this._stencilState.stencilFuncMask = mask;
  12467. };
  12468. /**
  12469. * Gets the current stencil operation when stencil fails
  12470. * @returns a number defining stencil operation to use when stencil fails
  12471. */
  12472. Engine.prototype.getStencilOperationFail = function () {
  12473. return this._stencilState.stencilOpStencilFail;
  12474. };
  12475. /**
  12476. * Gets the current stencil operation when depth fails
  12477. * @returns a number defining stencil operation to use when depth fails
  12478. */
  12479. Engine.prototype.getStencilOperationDepthFail = function () {
  12480. return this._stencilState.stencilOpDepthFail;
  12481. };
  12482. /**
  12483. * Gets the current stencil operation when stencil passes
  12484. * @returns a number defining stencil operation to use when stencil passes
  12485. */
  12486. Engine.prototype.getStencilOperationPass = function () {
  12487. return this._stencilState.stencilOpStencilDepthPass;
  12488. };
  12489. /**
  12490. * Sets the stencil operation to use when stencil fails
  12491. * @param operation defines the stencil operation to use when stencil fails
  12492. */
  12493. Engine.prototype.setStencilOperationFail = function (operation) {
  12494. this._stencilState.stencilOpStencilFail = operation;
  12495. };
  12496. /**
  12497. * Sets the stencil operation to use when depth fails
  12498. * @param operation defines the stencil operation to use when depth fails
  12499. */
  12500. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12501. this._stencilState.stencilOpDepthFail = operation;
  12502. };
  12503. /**
  12504. * Sets the stencil operation to use when stencil passes
  12505. * @param operation defines the stencil operation to use when stencil passes
  12506. */
  12507. Engine.prototype.setStencilOperationPass = function (operation) {
  12508. this._stencilState.stencilOpStencilDepthPass = operation;
  12509. };
  12510. /**
  12511. * Sets a boolean indicating if the dithering state is enabled or disabled
  12512. * @param value defines the dithering state
  12513. */
  12514. Engine.prototype.setDitheringState = function (value) {
  12515. if (value) {
  12516. this._gl.enable(this._gl.DITHER);
  12517. }
  12518. else {
  12519. this._gl.disable(this._gl.DITHER);
  12520. }
  12521. };
  12522. /**
  12523. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12524. * @param value defines the rasterizer state
  12525. */
  12526. Engine.prototype.setRasterizerState = function (value) {
  12527. if (value) {
  12528. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12529. }
  12530. else {
  12531. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12532. }
  12533. };
  12534. /**
  12535. * stop executing a render loop function and remove it from the execution array
  12536. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12537. */
  12538. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12539. if (!renderFunction) {
  12540. this._activeRenderLoops = [];
  12541. return;
  12542. }
  12543. var index = this._activeRenderLoops.indexOf(renderFunction);
  12544. if (index >= 0) {
  12545. this._activeRenderLoops.splice(index, 1);
  12546. }
  12547. };
  12548. /** @ignore */
  12549. Engine.prototype._renderLoop = function () {
  12550. if (!this._contextWasLost) {
  12551. var shouldRender = true;
  12552. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12553. shouldRender = false;
  12554. }
  12555. if (shouldRender) {
  12556. // Start new frame
  12557. this.beginFrame();
  12558. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12559. var renderFunction = this._activeRenderLoops[index];
  12560. renderFunction();
  12561. }
  12562. // Present
  12563. this.endFrame();
  12564. }
  12565. }
  12566. if (this._activeRenderLoops.length > 0) {
  12567. // Register new frame
  12568. var requester = null;
  12569. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12570. requester = this._vrDisplay;
  12571. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12572. }
  12573. else {
  12574. this._renderingQueueLaunched = false;
  12575. }
  12576. };
  12577. /**
  12578. * Register and execute a render loop. The engine can have more than one render function
  12579. * @param renderFunction defines the function to continuously execute
  12580. */
  12581. Engine.prototype.runRenderLoop = function (renderFunction) {
  12582. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12583. return;
  12584. }
  12585. this._activeRenderLoops.push(renderFunction);
  12586. if (!this._renderingQueueLaunched) {
  12587. this._renderingQueueLaunched = true;
  12588. this._bindedRenderFunction = this._renderLoop.bind(this);
  12589. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12590. }
  12591. };
  12592. /**
  12593. * Toggle full screen mode
  12594. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12595. * @param options defines an option object to be sent to the requestFullscreen function
  12596. */
  12597. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12598. if (this.isFullscreen) {
  12599. BABYLON.Tools.ExitFullscreen();
  12600. }
  12601. else {
  12602. this._pointerLockRequested = requestPointerLock;
  12603. if (this._renderingCanvas) {
  12604. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12605. }
  12606. }
  12607. };
  12608. /**
  12609. * Clear the current render buffer or the current render target (if any is set up)
  12610. * @param color defines the color to use
  12611. * @param backBuffer defines if the back buffer must be cleared
  12612. * @param depth defines if the depth buffer must be cleared
  12613. * @param stencil defines if the stencil buffer must be cleared
  12614. */
  12615. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12616. if (stencil === void 0) { stencil = false; }
  12617. this.applyStates();
  12618. var mode = 0;
  12619. if (backBuffer && color) {
  12620. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12621. mode |= this._gl.COLOR_BUFFER_BIT;
  12622. }
  12623. if (depth) {
  12624. this._gl.clearDepth(1.0);
  12625. mode |= this._gl.DEPTH_BUFFER_BIT;
  12626. }
  12627. if (stencil) {
  12628. this._gl.clearStencil(0);
  12629. mode |= this._gl.STENCIL_BUFFER_BIT;
  12630. }
  12631. this._gl.clear(mode);
  12632. };
  12633. /**
  12634. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12635. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12636. * @param y defines the y-coordinate of the corner of the clear rectangle
  12637. * @param width defines the width of the clear rectangle
  12638. * @param height defines the height of the clear rectangle
  12639. * @param clearColor defines the clear color
  12640. */
  12641. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12642. var gl = this._gl;
  12643. // Save state
  12644. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12645. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12646. // Change state
  12647. gl.enable(gl.SCISSOR_TEST);
  12648. gl.scissor(x, y, width, height);
  12649. // Clear
  12650. this.clear(clearColor, true, true, true);
  12651. // Restore state
  12652. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12653. if (curScissor === true) {
  12654. gl.enable(gl.SCISSOR_TEST);
  12655. }
  12656. else {
  12657. gl.disable(gl.SCISSOR_TEST);
  12658. }
  12659. };
  12660. /**
  12661. * Set the WebGL's viewport
  12662. * @param viewport defines the viewport element to be used
  12663. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12664. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12665. */
  12666. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12667. var width = requiredWidth || this.getRenderWidth();
  12668. var height = requiredHeight || this.getRenderHeight();
  12669. var x = viewport.x || 0;
  12670. var y = viewport.y || 0;
  12671. this._cachedViewport = viewport;
  12672. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12673. };
  12674. /**
  12675. * Directly set the WebGL Viewport
  12676. * @param x defines the x coordinate of the viewport (in screen space)
  12677. * @param y defines the y coordinate of the viewport (in screen space)
  12678. * @param width defines the width of the viewport (in screen space)
  12679. * @param height defines the height of the viewport (in screen space)
  12680. * @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
  12681. */
  12682. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12683. var currentViewport = this._cachedViewport;
  12684. this._cachedViewport = null;
  12685. this._gl.viewport(x, y, width, height);
  12686. return currentViewport;
  12687. };
  12688. /**
  12689. * Begin a new frame
  12690. */
  12691. Engine.prototype.beginFrame = function () {
  12692. this.onBeginFrameObservable.notifyObservers(this);
  12693. this._measureFps();
  12694. };
  12695. /**
  12696. * Enf the current frame
  12697. */
  12698. Engine.prototype.endFrame = function () {
  12699. // Force a flush in case we are using a bad OS.
  12700. if (this._badOS) {
  12701. this.flushFramebuffer();
  12702. }
  12703. // Submit frame to the vr device, if enabled
  12704. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12705. // TODO: We should only submit the frame if we read frameData successfully.
  12706. this._vrDisplay.submitFrame();
  12707. }
  12708. this.onEndFrameObservable.notifyObservers(this);
  12709. };
  12710. /**
  12711. * Resize the view according to the canvas' size
  12712. */
  12713. Engine.prototype.resize = function () {
  12714. // We're not resizing the size of the canvas while in VR mode & presenting
  12715. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12716. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12717. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12718. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12719. }
  12720. };
  12721. /**
  12722. * Force a specific size of the canvas
  12723. * @param width defines the new canvas' width
  12724. * @param height defines the new canvas' height
  12725. */
  12726. Engine.prototype.setSize = function (width, height) {
  12727. if (!this._renderingCanvas) {
  12728. return;
  12729. }
  12730. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12731. return;
  12732. }
  12733. this._renderingCanvas.width = width;
  12734. this._renderingCanvas.height = height;
  12735. for (var index = 0; index < this.scenes.length; index++) {
  12736. var scene = this.scenes[index];
  12737. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12738. var cam = scene.cameras[camIndex];
  12739. cam._currentRenderId = 0;
  12740. }
  12741. }
  12742. if (this.onResizeObservable.hasObservers) {
  12743. this.onResizeObservable.notifyObservers(this);
  12744. }
  12745. };
  12746. // WebVR functions
  12747. /**
  12748. * Gets a boolean indicating if a webVR device was detected
  12749. * @returns true if a webVR device was detected
  12750. */
  12751. Engine.prototype.isVRDevicePresent = function () {
  12752. return !!this._vrDisplay;
  12753. };
  12754. /**
  12755. * Gets the current webVR device
  12756. * @returns the current webVR device (or null)
  12757. */
  12758. Engine.prototype.getVRDevice = function () {
  12759. return this._vrDisplay;
  12760. };
  12761. /**
  12762. * Initializes a webVR display and starts listening to display change events
  12763. * The onVRDisplayChangedObservable will be notified upon these changes
  12764. * @returns The onVRDisplayChangedObservable
  12765. */
  12766. Engine.prototype.initWebVR = function () {
  12767. this.initWebVRAsync();
  12768. return this.onVRDisplayChangedObservable;
  12769. };
  12770. /**
  12771. * Initializes a webVR display and starts listening to display change events
  12772. * The onVRDisplayChangedObservable will be notified upon these changes
  12773. * @returns A promise containing a VRDisplay and if vr is supported
  12774. */
  12775. Engine.prototype.initWebVRAsync = function () {
  12776. var _this = this;
  12777. var notifyObservers = function () {
  12778. var eventArgs = {
  12779. vrDisplay: _this._vrDisplay,
  12780. vrSupported: _this._vrSupported
  12781. };
  12782. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12783. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12784. };
  12785. if (!this._onVrDisplayConnect) {
  12786. this._onVrDisplayConnect = function (event) {
  12787. _this._vrDisplay = event.display;
  12788. notifyObservers();
  12789. };
  12790. this._onVrDisplayDisconnect = function () {
  12791. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12792. _this._vrDisplay = undefined;
  12793. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12794. notifyObservers();
  12795. };
  12796. this._onVrDisplayPresentChange = function () {
  12797. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12798. };
  12799. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12800. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12801. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12802. }
  12803. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12804. this._webVRInitPromise.then(notifyObservers);
  12805. return this._webVRInitPromise;
  12806. };
  12807. /**
  12808. * Call this function to switch to webVR mode
  12809. * Will do nothing if webVR is not supported or if there is no webVR device
  12810. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12811. */
  12812. Engine.prototype.enableVR = function () {
  12813. var _this = this;
  12814. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12815. var onResolved = function () {
  12816. _this.onVRRequestPresentComplete.notifyObservers(true);
  12817. _this._onVRFullScreenTriggered();
  12818. };
  12819. var onRejected = function () {
  12820. _this.onVRRequestPresentComplete.notifyObservers(false);
  12821. };
  12822. this.onVRRequestPresentStart.notifyObservers(this);
  12823. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12824. }
  12825. };
  12826. /**
  12827. * Call this function to leave webVR mode
  12828. * Will do nothing if webVR is not supported or if there is no webVR device
  12829. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12830. */
  12831. Engine.prototype.disableVR = function () {
  12832. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12833. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12834. }
  12835. };
  12836. Engine.prototype._getVRDisplaysAsync = function () {
  12837. var _this = this;
  12838. return new Promise(function (res, rej) {
  12839. if (navigator.getVRDisplays) {
  12840. navigator.getVRDisplays().then(function (devices) {
  12841. _this._vrSupported = true;
  12842. // note that devices may actually be an empty array. This is fine;
  12843. // we expect this._vrDisplay to be undefined in this case.
  12844. _this._vrDisplay = devices[0];
  12845. res({
  12846. vrDisplay: _this._vrDisplay,
  12847. vrSupported: _this._vrSupported
  12848. });
  12849. });
  12850. }
  12851. else {
  12852. _this._vrDisplay = undefined;
  12853. _this._vrSupported = false;
  12854. res({
  12855. vrDisplay: _this._vrDisplay,
  12856. vrSupported: _this._vrSupported
  12857. });
  12858. }
  12859. });
  12860. };
  12861. /**
  12862. * Binds the frame buffer to the specified texture.
  12863. * @param texture The texture to render to or null for the default canvas
  12864. * @param faceIndex The face of the texture to render to in case of cube texture
  12865. * @param requiredWidth The width of the target to render to
  12866. * @param requiredHeight The height of the target to render to
  12867. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12868. * @param depthStencilTexture The depth stencil texture to use to render
  12869. */
  12870. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12871. if (this._currentRenderTarget) {
  12872. this.unBindFramebuffer(this._currentRenderTarget);
  12873. }
  12874. this._currentRenderTarget = texture;
  12875. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12876. var gl = this._gl;
  12877. if (texture.isCube) {
  12878. if (faceIndex === undefined) {
  12879. faceIndex = 0;
  12880. }
  12881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12882. if (depthStencilTexture) {
  12883. if (depthStencilTexture._generateStencilBuffer) {
  12884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12885. }
  12886. else {
  12887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12888. }
  12889. }
  12890. }
  12891. if (this._cachedViewport && !forceFullscreenViewport) {
  12892. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12893. }
  12894. else {
  12895. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12896. }
  12897. this.wipeCaches();
  12898. };
  12899. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12900. if (this._currentFramebuffer !== framebuffer) {
  12901. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12902. this._currentFramebuffer = framebuffer;
  12903. }
  12904. };
  12905. /**
  12906. * Unbind the current render target texture from the webGL context
  12907. * @param texture defines the render target texture to unbind
  12908. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12909. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12910. */
  12911. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12912. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12913. this._currentRenderTarget = null;
  12914. // If MSAA, we need to bitblt back to main texture
  12915. var gl = this._gl;
  12916. if (texture._MSAAFramebuffer) {
  12917. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12918. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12919. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12920. }
  12921. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12922. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12923. gl.generateMipmap(gl.TEXTURE_2D);
  12924. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12925. }
  12926. if (onBeforeUnbind) {
  12927. if (texture._MSAAFramebuffer) {
  12928. // Bind the correct framebuffer
  12929. this.bindUnboundFramebuffer(texture._framebuffer);
  12930. }
  12931. onBeforeUnbind();
  12932. }
  12933. this.bindUnboundFramebuffer(null);
  12934. };
  12935. /**
  12936. * Unbind a list of render target textures from the webGL context
  12937. * This is used only when drawBuffer extension or webGL2 are active
  12938. * @param textures defines the render target textures to unbind
  12939. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12940. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12941. */
  12942. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12943. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12944. this._currentRenderTarget = null;
  12945. // If MSAA, we need to bitblt back to main texture
  12946. var gl = this._gl;
  12947. if (textures[0]._MSAAFramebuffer) {
  12948. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12949. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12950. var attachments = textures[0]._attachments;
  12951. if (!attachments) {
  12952. attachments = new Array(textures.length);
  12953. textures[0]._attachments = attachments;
  12954. }
  12955. for (var i = 0; i < textures.length; i++) {
  12956. var texture = textures[i];
  12957. for (var j = 0; j < attachments.length; j++) {
  12958. attachments[j] = gl.NONE;
  12959. }
  12960. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12961. gl.readBuffer(attachments[i]);
  12962. gl.drawBuffers(attachments);
  12963. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12964. }
  12965. for (var i = 0; i < attachments.length; i++) {
  12966. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12967. }
  12968. gl.drawBuffers(attachments);
  12969. }
  12970. for (var i = 0; i < textures.length; i++) {
  12971. var texture = textures[i];
  12972. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12973. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12974. gl.generateMipmap(gl.TEXTURE_2D);
  12975. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12976. }
  12977. }
  12978. if (onBeforeUnbind) {
  12979. if (textures[0]._MSAAFramebuffer) {
  12980. // Bind the correct framebuffer
  12981. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12982. }
  12983. onBeforeUnbind();
  12984. }
  12985. this.bindUnboundFramebuffer(null);
  12986. };
  12987. /**
  12988. * Force the mipmap generation for the given render target texture
  12989. * @param texture defines the render target texture to use
  12990. */
  12991. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12992. if (texture.generateMipMaps) {
  12993. var gl = this._gl;
  12994. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12995. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12996. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12997. }
  12998. };
  12999. /**
  13000. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13001. */
  13002. Engine.prototype.flushFramebuffer = function () {
  13003. this._gl.flush();
  13004. };
  13005. /**
  13006. * Unbind the current render target and bind the default framebuffer
  13007. */
  13008. Engine.prototype.restoreDefaultFramebuffer = function () {
  13009. if (this._currentRenderTarget) {
  13010. this.unBindFramebuffer(this._currentRenderTarget);
  13011. }
  13012. else {
  13013. this.bindUnboundFramebuffer(null);
  13014. }
  13015. if (this._cachedViewport) {
  13016. this.setViewport(this._cachedViewport);
  13017. }
  13018. this.wipeCaches();
  13019. };
  13020. // UBOs
  13021. /**
  13022. * Create an uniform buffer
  13023. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13024. * @param elements defines the content of the uniform buffer
  13025. * @returns the webGL uniform buffer
  13026. */
  13027. Engine.prototype.createUniformBuffer = function (elements) {
  13028. var ubo = this._gl.createBuffer();
  13029. if (!ubo) {
  13030. throw new Error("Unable to create uniform buffer");
  13031. }
  13032. this.bindUniformBuffer(ubo);
  13033. if (elements instanceof Float32Array) {
  13034. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13035. }
  13036. else {
  13037. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13038. }
  13039. this.bindUniformBuffer(null);
  13040. ubo.references = 1;
  13041. return ubo;
  13042. };
  13043. /**
  13044. * Create a dynamic uniform buffer
  13045. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13046. * @param elements defines the content of the uniform buffer
  13047. * @returns the webGL uniform buffer
  13048. */
  13049. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13050. var ubo = this._gl.createBuffer();
  13051. if (!ubo) {
  13052. throw new Error("Unable to create dynamic uniform buffer");
  13053. }
  13054. this.bindUniformBuffer(ubo);
  13055. if (elements instanceof Float32Array) {
  13056. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13057. }
  13058. else {
  13059. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13060. }
  13061. this.bindUniformBuffer(null);
  13062. ubo.references = 1;
  13063. return ubo;
  13064. };
  13065. /**
  13066. * Update an existing uniform buffer
  13067. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13068. * @param uniformBuffer defines the target uniform buffer
  13069. * @param elements defines the content to update
  13070. * @param offset defines the offset in the uniform buffer where update should start
  13071. * @param count defines the size of the data to update
  13072. */
  13073. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13074. this.bindUniformBuffer(uniformBuffer);
  13075. if (offset === undefined) {
  13076. offset = 0;
  13077. }
  13078. if (count === undefined) {
  13079. if (elements instanceof Float32Array) {
  13080. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13081. }
  13082. else {
  13083. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13084. }
  13085. }
  13086. else {
  13087. if (elements instanceof Float32Array) {
  13088. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13089. }
  13090. else {
  13091. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13092. }
  13093. }
  13094. this.bindUniformBuffer(null);
  13095. };
  13096. // VBOs
  13097. Engine.prototype._resetVertexBufferBinding = function () {
  13098. this.bindArrayBuffer(null);
  13099. this._cachedVertexBuffers = null;
  13100. };
  13101. /**
  13102. * Creates a vertex buffer
  13103. * @param data the data for the vertex buffer
  13104. * @returns the new WebGL static buffer
  13105. */
  13106. Engine.prototype.createVertexBuffer = function (data) {
  13107. var vbo = this._gl.createBuffer();
  13108. if (!vbo) {
  13109. throw new Error("Unable to create vertex buffer");
  13110. }
  13111. this.bindArrayBuffer(vbo);
  13112. if (data instanceof Array) {
  13113. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13114. }
  13115. else {
  13116. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13117. }
  13118. this._resetVertexBufferBinding();
  13119. vbo.references = 1;
  13120. return vbo;
  13121. };
  13122. /**
  13123. * Creates a dynamic vertex buffer
  13124. * @param data the data for the dynamic vertex buffer
  13125. * @returns the new WebGL dynamic buffer
  13126. */
  13127. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13128. var vbo = this._gl.createBuffer();
  13129. if (!vbo) {
  13130. throw new Error("Unable to create dynamic vertex buffer");
  13131. }
  13132. this.bindArrayBuffer(vbo);
  13133. if (data instanceof Array) {
  13134. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13135. }
  13136. else {
  13137. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13138. }
  13139. this._resetVertexBufferBinding();
  13140. vbo.references = 1;
  13141. return vbo;
  13142. };
  13143. /**
  13144. * Update a dynamic index buffer
  13145. * @param indexBuffer defines the target index buffer
  13146. * @param indices defines the data to update
  13147. * @param offset defines the offset in the target index buffer where update should start
  13148. */
  13149. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13150. if (offset === void 0) { offset = 0; }
  13151. // Force cache update
  13152. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13153. this.bindIndexBuffer(indexBuffer);
  13154. var arrayBuffer;
  13155. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13156. arrayBuffer = indices;
  13157. }
  13158. else {
  13159. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13160. }
  13161. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13162. this._resetIndexBufferBinding();
  13163. };
  13164. /**
  13165. * Updates a dynamic vertex buffer.
  13166. * @param vertexBuffer the vertex buffer to update
  13167. * @param data the data used to update the vertex buffer
  13168. * @param byteOffset the byte offset of the data
  13169. * @param byteLength the byte length of the data
  13170. */
  13171. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13172. this.bindArrayBuffer(vertexBuffer);
  13173. if (byteOffset === undefined) {
  13174. byteOffset = 0;
  13175. }
  13176. if (byteLength === undefined) {
  13177. if (data instanceof Array) {
  13178. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13179. }
  13180. else {
  13181. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13182. }
  13183. }
  13184. else {
  13185. if (data instanceof Array) {
  13186. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13187. }
  13188. else {
  13189. if (data instanceof ArrayBuffer) {
  13190. data = new Uint8Array(data, byteOffset, byteLength);
  13191. }
  13192. else {
  13193. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13194. }
  13195. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13196. }
  13197. }
  13198. this._resetVertexBufferBinding();
  13199. };
  13200. Engine.prototype._resetIndexBufferBinding = function () {
  13201. this.bindIndexBuffer(null);
  13202. this._cachedIndexBuffer = null;
  13203. };
  13204. /**
  13205. * Creates a new index buffer
  13206. * @param indices defines the content of the index buffer
  13207. * @param updatable defines if the index buffer must be updatable
  13208. * @returns a new webGL buffer
  13209. */
  13210. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13211. var vbo = this._gl.createBuffer();
  13212. if (!vbo) {
  13213. throw new Error("Unable to create index buffer");
  13214. }
  13215. this.bindIndexBuffer(vbo);
  13216. // Check for 32 bits indices
  13217. var arrayBuffer;
  13218. var need32Bits = false;
  13219. if (indices instanceof Uint16Array) {
  13220. arrayBuffer = indices;
  13221. }
  13222. else {
  13223. //check 32 bit support
  13224. if (this._caps.uintIndices) {
  13225. if (indices instanceof Uint32Array) {
  13226. arrayBuffer = indices;
  13227. need32Bits = true;
  13228. }
  13229. else {
  13230. //number[] or Int32Array, check if 32 bit is necessary
  13231. for (var index = 0; index < indices.length; index++) {
  13232. if (indices[index] > 65535) {
  13233. need32Bits = true;
  13234. break;
  13235. }
  13236. }
  13237. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13238. }
  13239. }
  13240. else {
  13241. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13242. arrayBuffer = new Uint16Array(indices);
  13243. }
  13244. }
  13245. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13246. this._resetIndexBufferBinding();
  13247. vbo.references = 1;
  13248. vbo.is32Bits = need32Bits;
  13249. return vbo;
  13250. };
  13251. /**
  13252. * Bind a webGL buffer to the webGL context
  13253. * @param buffer defines the buffer to bind
  13254. */
  13255. Engine.prototype.bindArrayBuffer = function (buffer) {
  13256. if (!this._vaoRecordInProgress) {
  13257. this._unbindVertexArrayObject();
  13258. }
  13259. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13260. };
  13261. /**
  13262. * Bind an uniform buffer to the current webGL context
  13263. * @param buffer defines the buffer to bind
  13264. */
  13265. Engine.prototype.bindUniformBuffer = function (buffer) {
  13266. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13267. };
  13268. /**
  13269. * Bind a buffer to the current webGL context at a given location
  13270. * @param buffer defines the buffer to bind
  13271. * @param location defines the index where to bind the buffer
  13272. */
  13273. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13274. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13275. };
  13276. /**
  13277. * Bind a specific block at a given index in a specific shader program
  13278. * @param shaderProgram defines the shader program
  13279. * @param blockName defines the block name
  13280. * @param index defines the index where to bind the block
  13281. */
  13282. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13283. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13284. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13285. };
  13286. ;
  13287. Engine.prototype.bindIndexBuffer = function (buffer) {
  13288. if (!this._vaoRecordInProgress) {
  13289. this._unbindVertexArrayObject();
  13290. }
  13291. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13292. };
  13293. Engine.prototype.bindBuffer = function (buffer, target) {
  13294. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13295. this._gl.bindBuffer(target, buffer);
  13296. this._currentBoundBuffer[target] = buffer;
  13297. }
  13298. };
  13299. /**
  13300. * update the bound buffer with the given data
  13301. * @param data defines the data to update
  13302. */
  13303. Engine.prototype.updateArrayBuffer = function (data) {
  13304. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13305. };
  13306. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13307. var pointer = this._currentBufferPointers[indx];
  13308. var changed = false;
  13309. if (!pointer.active) {
  13310. changed = true;
  13311. pointer.active = true;
  13312. pointer.index = indx;
  13313. pointer.size = size;
  13314. pointer.type = type;
  13315. pointer.normalized = normalized;
  13316. pointer.stride = stride;
  13317. pointer.offset = offset;
  13318. pointer.buffer = buffer;
  13319. }
  13320. else {
  13321. if (pointer.buffer !== buffer) {
  13322. pointer.buffer = buffer;
  13323. changed = true;
  13324. }
  13325. if (pointer.size !== size) {
  13326. pointer.size = size;
  13327. changed = true;
  13328. }
  13329. if (pointer.type !== type) {
  13330. pointer.type = type;
  13331. changed = true;
  13332. }
  13333. if (pointer.normalized !== normalized) {
  13334. pointer.normalized = normalized;
  13335. changed = true;
  13336. }
  13337. if (pointer.stride !== stride) {
  13338. pointer.stride = stride;
  13339. changed = true;
  13340. }
  13341. if (pointer.offset !== offset) {
  13342. pointer.offset = offset;
  13343. changed = true;
  13344. }
  13345. }
  13346. if (changed || this._vaoRecordInProgress) {
  13347. this.bindArrayBuffer(buffer);
  13348. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13349. }
  13350. };
  13351. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13352. if (indexBuffer == null) {
  13353. return;
  13354. }
  13355. if (this._cachedIndexBuffer !== indexBuffer) {
  13356. this._cachedIndexBuffer = indexBuffer;
  13357. this.bindIndexBuffer(indexBuffer);
  13358. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13359. }
  13360. };
  13361. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13362. var attributes = effect.getAttributesNames();
  13363. if (!this._vaoRecordInProgress) {
  13364. this._unbindVertexArrayObject();
  13365. }
  13366. this.unbindAllAttributes();
  13367. for (var index = 0; index < attributes.length; index++) {
  13368. var order = effect.getAttributeLocation(index);
  13369. if (order >= 0) {
  13370. var vertexBuffer = vertexBuffers[attributes[index]];
  13371. if (!vertexBuffer) {
  13372. continue;
  13373. }
  13374. this._gl.enableVertexAttribArray(order);
  13375. if (!this._vaoRecordInProgress) {
  13376. this._vertexAttribArraysEnabled[order] = true;
  13377. }
  13378. var buffer = vertexBuffer.getBuffer();
  13379. if (buffer) {
  13380. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13381. if (vertexBuffer.getIsInstanced()) {
  13382. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13383. if (!this._vaoRecordInProgress) {
  13384. this._currentInstanceLocations.push(order);
  13385. this._currentInstanceBuffers.push(buffer);
  13386. }
  13387. }
  13388. }
  13389. }
  13390. }
  13391. };
  13392. /**
  13393. * Records a vertex array object
  13394. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13395. * @param vertexBuffers defines the list of vertex buffers to store
  13396. * @param indexBuffer defines the index buffer to store
  13397. * @param effect defines the effect to store
  13398. * @returns the new vertex array object
  13399. */
  13400. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13401. var vao = this._gl.createVertexArray();
  13402. this._vaoRecordInProgress = true;
  13403. this._gl.bindVertexArray(vao);
  13404. this._mustWipeVertexAttributes = true;
  13405. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13406. this.bindIndexBuffer(indexBuffer);
  13407. this._vaoRecordInProgress = false;
  13408. this._gl.bindVertexArray(null);
  13409. return vao;
  13410. };
  13411. /**
  13412. * Bind a specific vertex array object
  13413. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13414. * @param vertexArrayObject defines the vertex array object to bind
  13415. * @param indexBuffer defines the index buffer to bind
  13416. */
  13417. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13418. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13419. this._cachedVertexArrayObject = vertexArrayObject;
  13420. this._gl.bindVertexArray(vertexArrayObject);
  13421. this._cachedVertexBuffers = null;
  13422. this._cachedIndexBuffer = null;
  13423. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13424. this._mustWipeVertexAttributes = true;
  13425. }
  13426. };
  13427. /**
  13428. * Bind webGl buffers directly to the webGL context
  13429. * @param vertexBuffer defines the vertex buffer to bind
  13430. * @param indexBuffer defines the index buffer to bind
  13431. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13432. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13433. * @param effect defines the effect associated with the vertex buffer
  13434. */
  13435. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13436. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13437. this._cachedVertexBuffers = vertexBuffer;
  13438. this._cachedEffectForVertexBuffers = effect;
  13439. var attributesCount = effect.getAttributesCount();
  13440. this._unbindVertexArrayObject();
  13441. this.unbindAllAttributes();
  13442. var offset = 0;
  13443. for (var index = 0; index < attributesCount; index++) {
  13444. if (index < vertexDeclaration.length) {
  13445. var order = effect.getAttributeLocation(index);
  13446. if (order >= 0) {
  13447. this._gl.enableVertexAttribArray(order);
  13448. this._vertexAttribArraysEnabled[order] = true;
  13449. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13450. }
  13451. offset += vertexDeclaration[index] * 4;
  13452. }
  13453. }
  13454. }
  13455. this._bindIndexBufferWithCache(indexBuffer);
  13456. };
  13457. Engine.prototype._unbindVertexArrayObject = function () {
  13458. if (!this._cachedVertexArrayObject) {
  13459. return;
  13460. }
  13461. this._cachedVertexArrayObject = null;
  13462. this._gl.bindVertexArray(null);
  13463. };
  13464. /**
  13465. * Bind a list of vertex buffers to the webGL context
  13466. * @param vertexBuffers defines the list of vertex buffers to bind
  13467. * @param indexBuffer defines the index buffer to bind
  13468. * @param effect defines the effect associated with the vertex buffers
  13469. */
  13470. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13471. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13472. this._cachedVertexBuffers = vertexBuffers;
  13473. this._cachedEffectForVertexBuffers = effect;
  13474. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13475. }
  13476. this._bindIndexBufferWithCache(indexBuffer);
  13477. };
  13478. /**
  13479. * Unbind all instance attributes
  13480. */
  13481. Engine.prototype.unbindInstanceAttributes = function () {
  13482. var boundBuffer;
  13483. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13484. var instancesBuffer = this._currentInstanceBuffers[i];
  13485. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13486. boundBuffer = instancesBuffer;
  13487. this.bindArrayBuffer(instancesBuffer);
  13488. }
  13489. var offsetLocation = this._currentInstanceLocations[i];
  13490. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13491. }
  13492. this._currentInstanceBuffers.length = 0;
  13493. this._currentInstanceLocations.length = 0;
  13494. };
  13495. /**
  13496. * Release and free the memory of a vertex array object
  13497. * @param vao defines the vertex array object to delete
  13498. */
  13499. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13500. this._gl.deleteVertexArray(vao);
  13501. };
  13502. /** @ignore */
  13503. Engine.prototype._releaseBuffer = function (buffer) {
  13504. buffer.references--;
  13505. if (buffer.references === 0) {
  13506. this._gl.deleteBuffer(buffer);
  13507. return true;
  13508. }
  13509. return false;
  13510. };
  13511. /**
  13512. * Creates a webGL buffer to use with instanciation
  13513. * @param capacity defines the size of the buffer
  13514. * @returns the webGL buffer
  13515. */
  13516. Engine.prototype.createInstancesBuffer = function (capacity) {
  13517. var buffer = this._gl.createBuffer();
  13518. if (!buffer) {
  13519. throw new Error("Unable to create instance buffer");
  13520. }
  13521. buffer.capacity = capacity;
  13522. this.bindArrayBuffer(buffer);
  13523. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13524. return buffer;
  13525. };
  13526. /**
  13527. * Delete a webGL buffer used with instanciation
  13528. * @param buffer defines the webGL buffer to delete
  13529. */
  13530. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13531. this._gl.deleteBuffer(buffer);
  13532. };
  13533. /**
  13534. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13535. * @param instancesBuffer defines the webGL buffer to update and bind
  13536. * @param data defines the data to store in the buffer
  13537. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13538. */
  13539. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13540. this.bindArrayBuffer(instancesBuffer);
  13541. if (data) {
  13542. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13543. }
  13544. if (offsetLocations[0].index !== undefined) {
  13545. var stride = 0;
  13546. for (var i = 0; i < offsetLocations.length; i++) {
  13547. var ai = offsetLocations[i];
  13548. stride += ai.attributeSize * 4;
  13549. }
  13550. for (var i = 0; i < offsetLocations.length; i++) {
  13551. var ai = offsetLocations[i];
  13552. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13553. this._gl.enableVertexAttribArray(ai.index);
  13554. this._vertexAttribArraysEnabled[ai.index] = true;
  13555. }
  13556. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13557. this._gl.vertexAttribDivisor(ai.index, 1);
  13558. this._currentInstanceLocations.push(ai.index);
  13559. this._currentInstanceBuffers.push(instancesBuffer);
  13560. }
  13561. }
  13562. else {
  13563. for (var index = 0; index < 4; index++) {
  13564. var offsetLocation = offsetLocations[index];
  13565. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13566. this._gl.enableVertexAttribArray(offsetLocation);
  13567. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13568. }
  13569. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13570. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13571. this._currentInstanceLocations.push(offsetLocation);
  13572. this._currentInstanceBuffers.push(instancesBuffer);
  13573. }
  13574. }
  13575. };
  13576. /**
  13577. * Apply all cached states (depth, culling, stencil and alpha)
  13578. */
  13579. Engine.prototype.applyStates = function () {
  13580. this._depthCullingState.apply(this._gl);
  13581. this._stencilState.apply(this._gl);
  13582. this._alphaState.apply(this._gl);
  13583. };
  13584. /**
  13585. * Send a draw order
  13586. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13587. * @param indexStart defines the starting index
  13588. * @param indexCount defines the number of index to draw
  13589. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13590. */
  13591. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13592. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13593. };
  13594. /**
  13595. * Draw a list of points
  13596. * @param verticesStart defines the index of first vertex to draw
  13597. * @param verticesCount defines the count of vertices to draw
  13598. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13599. */
  13600. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13601. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13602. };
  13603. /**
  13604. * Draw a list of unindexed primitives
  13605. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13606. * @param verticesStart defines the index of first vertex to draw
  13607. * @param verticesCount defines the count of vertices to draw
  13608. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13609. */
  13610. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13611. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13612. };
  13613. /**
  13614. * Draw a list of indexed primitives
  13615. * @param fillMode defines the primitive to use
  13616. * @param indexStart defines the starting index
  13617. * @param indexCount defines the number of index to draw
  13618. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13619. */
  13620. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13621. // Apply states
  13622. this.applyStates();
  13623. this._drawCalls.addCount(1, false);
  13624. // Render
  13625. var drawMode = this._drawMode(fillMode);
  13626. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13627. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13628. if (instancesCount) {
  13629. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13630. }
  13631. else {
  13632. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13633. }
  13634. };
  13635. /**
  13636. * Draw a list of unindexed primitives
  13637. * @param fillMode defines the primitive to use
  13638. * @param verticesStart defines the index of first vertex to draw
  13639. * @param verticesCount defines the count of vertices to draw
  13640. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13641. */
  13642. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13643. // Apply states
  13644. this.applyStates();
  13645. this._drawCalls.addCount(1, false);
  13646. var drawMode = this._drawMode(fillMode);
  13647. if (instancesCount) {
  13648. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13649. }
  13650. else {
  13651. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13652. }
  13653. };
  13654. Engine.prototype._drawMode = function (fillMode) {
  13655. switch (fillMode) {
  13656. // Triangle views
  13657. case BABYLON.Material.TriangleFillMode:
  13658. return this._gl.TRIANGLES;
  13659. case BABYLON.Material.PointFillMode:
  13660. return this._gl.POINTS;
  13661. case BABYLON.Material.WireFrameFillMode:
  13662. return this._gl.LINES;
  13663. // Draw modes
  13664. case BABYLON.Material.PointListDrawMode:
  13665. return this._gl.POINTS;
  13666. case BABYLON.Material.LineListDrawMode:
  13667. return this._gl.LINES;
  13668. case BABYLON.Material.LineLoopDrawMode:
  13669. return this._gl.LINE_LOOP;
  13670. case BABYLON.Material.LineStripDrawMode:
  13671. return this._gl.LINE_STRIP;
  13672. case BABYLON.Material.TriangleStripDrawMode:
  13673. return this._gl.TRIANGLE_STRIP;
  13674. case BABYLON.Material.TriangleFanDrawMode:
  13675. return this._gl.TRIANGLE_FAN;
  13676. default:
  13677. return this._gl.TRIANGLES;
  13678. }
  13679. };
  13680. // Shaders
  13681. /** @ignore */
  13682. Engine.prototype._releaseEffect = function (effect) {
  13683. if (this._compiledEffects[effect._key]) {
  13684. delete this._compiledEffects[effect._key];
  13685. this._deleteProgram(effect.getProgram());
  13686. }
  13687. };
  13688. /** @ignore */
  13689. Engine.prototype._deleteProgram = function (program) {
  13690. if (program) {
  13691. program.__SPECTOR_rebuildProgram = null;
  13692. if (program.transformFeedback) {
  13693. this.deleteTransformFeedback(program.transformFeedback);
  13694. program.transformFeedback = null;
  13695. }
  13696. this._gl.deleteProgram(program);
  13697. }
  13698. };
  13699. /**
  13700. * Create a new effect (used to store vertex/fragment shaders)
  13701. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13702. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13703. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13704. * @param samplers defines an array of string used to represent textures
  13705. * @param defines defines the string containing the defines to use to compile the shaders
  13706. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13707. * @param onCompiled defines a function to call when the effect creation is successful
  13708. * @param onError defines a function to call when the effect creation has failed
  13709. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13710. * @returns the new Effect
  13711. */
  13712. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13713. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13714. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13715. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13716. if (this._compiledEffects[name]) {
  13717. var compiledEffect = this._compiledEffects[name];
  13718. if (onCompiled && compiledEffect.isReady()) {
  13719. onCompiled(compiledEffect);
  13720. }
  13721. return compiledEffect;
  13722. }
  13723. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13724. effect._key = name;
  13725. this._compiledEffects[name] = effect;
  13726. return effect;
  13727. };
  13728. /**
  13729. * Create an effect to use with particle systems
  13730. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13731. * @param uniformsNames defines a list of attribute names
  13732. * @param samplers defines an array of string used to represent textures
  13733. * @param defines defines the string containing the defines to use to compile the shaders
  13734. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13735. * @param onCompiled defines a function to call when the effect creation is successful
  13736. * @param onError defines a function to call when the effect creation has failed
  13737. * @returns the new Effect
  13738. */
  13739. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13740. if (uniformsNames === void 0) { uniformsNames = []; }
  13741. if (samplers === void 0) { samplers = []; }
  13742. if (defines === void 0) { defines = ""; }
  13743. return this.createEffect({
  13744. vertex: "particles",
  13745. fragmentElement: fragmentName
  13746. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13747. };
  13748. /**
  13749. * Directly creates a webGL program
  13750. * @param vertexCode defines the vertex shader code to use
  13751. * @param fragmentCode defines the fragment shader code to use
  13752. * @param context defines the webGL context to use (if not set, the current one will be used)
  13753. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13754. * @returns the new webGL program
  13755. */
  13756. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13757. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13758. context = context || this._gl;
  13759. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13760. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13761. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13762. };
  13763. /**
  13764. * Creates a webGL program
  13765. * @param vertexCode defines the vertex shader code to use
  13766. * @param fragmentCode defines the fragment shader code to use
  13767. * @param defines defines the string containing the defines to use to compile the shaders
  13768. * @param context defines the webGL context to use (if not set, the current one will be used)
  13769. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13770. * @returns the new webGL program
  13771. */
  13772. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13773. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13774. context = context || this._gl;
  13775. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13776. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13777. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13778. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13779. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13780. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13781. return program;
  13782. };
  13783. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13784. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13785. var shaderProgram = context.createProgram();
  13786. if (!shaderProgram) {
  13787. throw new Error("Unable to create program");
  13788. }
  13789. context.attachShader(shaderProgram, vertexShader);
  13790. context.attachShader(shaderProgram, fragmentShader);
  13791. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13792. var transformFeedback = this.createTransformFeedback();
  13793. this.bindTransformFeedback(transformFeedback);
  13794. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13795. shaderProgram.transformFeedback = transformFeedback;
  13796. }
  13797. context.linkProgram(shaderProgram);
  13798. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13799. this.bindTransformFeedback(null);
  13800. }
  13801. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13802. if (!linked) {
  13803. context.validateProgram(shaderProgram);
  13804. var error = context.getProgramInfoLog(shaderProgram);
  13805. if (error) {
  13806. throw new Error(error);
  13807. }
  13808. }
  13809. context.deleteShader(vertexShader);
  13810. context.deleteShader(fragmentShader);
  13811. return shaderProgram;
  13812. };
  13813. /**
  13814. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13815. * @param shaderProgram defines the webGL program to use
  13816. * @param uniformsNames defines the list of uniform names
  13817. * @returns an array of webGL uniform locations
  13818. */
  13819. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13820. var results = new Array();
  13821. for (var index = 0; index < uniformsNames.length; index++) {
  13822. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13823. }
  13824. return results;
  13825. };
  13826. /**
  13827. * Gets the lsit of active attributes for a given webGL program
  13828. * @param shaderProgram defines the webGL program to use
  13829. * @param attributesNames defines the list of attribute names to get
  13830. * @returns an array of indices indicating the offset of each attribute
  13831. */
  13832. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13833. var results = [];
  13834. for (var index = 0; index < attributesNames.length; index++) {
  13835. try {
  13836. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13837. }
  13838. catch (e) {
  13839. results.push(-1);
  13840. }
  13841. }
  13842. return results;
  13843. };
  13844. /**
  13845. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13846. * @param effect defines the effect to activate
  13847. */
  13848. Engine.prototype.enableEffect = function (effect) {
  13849. if (!effect) {
  13850. return;
  13851. }
  13852. // Use program
  13853. this.bindSamplers(effect);
  13854. this._currentEffect = effect;
  13855. if (effect.onBind) {
  13856. effect.onBind(effect);
  13857. }
  13858. effect.onBindObservable.notifyObservers(effect);
  13859. };
  13860. /**
  13861. * Set the value of an uniform to an array of int32
  13862. * @param uniform defines the webGL uniform location where to store the value
  13863. * @param array defines the array of int32 to store
  13864. */
  13865. Engine.prototype.setIntArray = function (uniform, array) {
  13866. if (!uniform)
  13867. return;
  13868. this._gl.uniform1iv(uniform, array);
  13869. };
  13870. /**
  13871. * Set the value of an uniform to an array of int32 (stored as vec2)
  13872. * @param uniform defines the webGL uniform location where to store the value
  13873. * @param array defines the array of int32 to store
  13874. */
  13875. Engine.prototype.setIntArray2 = function (uniform, array) {
  13876. if (!uniform || array.length % 2 !== 0)
  13877. return;
  13878. this._gl.uniform2iv(uniform, array);
  13879. };
  13880. /**
  13881. * Set the value of an uniform to an array of int32 (stored as vec3)
  13882. * @param uniform defines the webGL uniform location where to store the value
  13883. * @param array defines the array of int32 to store
  13884. */
  13885. Engine.prototype.setIntArray3 = function (uniform, array) {
  13886. if (!uniform || array.length % 3 !== 0)
  13887. return;
  13888. this._gl.uniform3iv(uniform, array);
  13889. };
  13890. /**
  13891. * Set the value of an uniform to an array of int32 (stored as vec4)
  13892. * @param uniform defines the webGL uniform location where to store the value
  13893. * @param array defines the array of int32 to store
  13894. */
  13895. Engine.prototype.setIntArray4 = function (uniform, array) {
  13896. if (!uniform || array.length % 4 !== 0)
  13897. return;
  13898. this._gl.uniform4iv(uniform, array);
  13899. };
  13900. /**
  13901. * Set the value of an uniform to an array of float32
  13902. * @param uniform defines the webGL uniform location where to store the value
  13903. * @param array defines the array of float32 to store
  13904. */
  13905. Engine.prototype.setFloatArray = function (uniform, array) {
  13906. if (!uniform)
  13907. return;
  13908. this._gl.uniform1fv(uniform, array);
  13909. };
  13910. /**
  13911. * Set the value of an uniform to an array of float32 (stored as vec2)
  13912. * @param uniform defines the webGL uniform location where to store the value
  13913. * @param array defines the array of float32 to store
  13914. */
  13915. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13916. if (!uniform || array.length % 2 !== 0)
  13917. return;
  13918. this._gl.uniform2fv(uniform, array);
  13919. };
  13920. /**
  13921. * Set the value of an uniform to an array of float32 (stored as vec3)
  13922. * @param uniform defines the webGL uniform location where to store the value
  13923. * @param array defines the array of float32 to store
  13924. */
  13925. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13926. if (!uniform || array.length % 3 !== 0)
  13927. return;
  13928. this._gl.uniform3fv(uniform, array);
  13929. };
  13930. /**
  13931. * Set the value of an uniform to an array of float32 (stored as vec4)
  13932. * @param uniform defines the webGL uniform location where to store the value
  13933. * @param array defines the array of float32 to store
  13934. */
  13935. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13936. if (!uniform || array.length % 4 !== 0)
  13937. return;
  13938. this._gl.uniform4fv(uniform, array);
  13939. };
  13940. /**
  13941. * Set the value of an uniform to an array of number
  13942. * @param uniform defines the webGL uniform location where to store the value
  13943. * @param array defines the array of number to store
  13944. */
  13945. Engine.prototype.setArray = function (uniform, array) {
  13946. if (!uniform)
  13947. return;
  13948. this._gl.uniform1fv(uniform, array);
  13949. };
  13950. /**
  13951. * Set the value of an uniform to an array of number (stored as vec2)
  13952. * @param uniform defines the webGL uniform location where to store the value
  13953. * @param array defines the array of number to store
  13954. */
  13955. Engine.prototype.setArray2 = function (uniform, array) {
  13956. if (!uniform || array.length % 2 !== 0)
  13957. return;
  13958. this._gl.uniform2fv(uniform, array);
  13959. };
  13960. /**
  13961. * Set the value of an uniform to an array of number (stored as vec3)
  13962. * @param uniform defines the webGL uniform location where to store the value
  13963. * @param array defines the array of number to store
  13964. */
  13965. Engine.prototype.setArray3 = function (uniform, array) {
  13966. if (!uniform || array.length % 3 !== 0)
  13967. return;
  13968. this._gl.uniform3fv(uniform, array);
  13969. };
  13970. /**
  13971. * Set the value of an uniform to an array of number (stored as vec4)
  13972. * @param uniform defines the webGL uniform location where to store the value
  13973. * @param array defines the array of number to store
  13974. */
  13975. Engine.prototype.setArray4 = function (uniform, array) {
  13976. if (!uniform || array.length % 4 !== 0)
  13977. return;
  13978. this._gl.uniform4fv(uniform, array);
  13979. };
  13980. /**
  13981. * Set the value of an uniform to an array of float32 (stored as matrices)
  13982. * @param uniform defines the webGL uniform location where to store the value
  13983. * @param matrices defines the array of float32 to store
  13984. */
  13985. Engine.prototype.setMatrices = function (uniform, matrices) {
  13986. if (!uniform)
  13987. return;
  13988. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13989. };
  13990. /**
  13991. * Set the value of an uniform to a matrix
  13992. * @param uniform defines the webGL uniform location where to store the value
  13993. * @param matrix defines the matrix to store
  13994. */
  13995. Engine.prototype.setMatrix = function (uniform, matrix) {
  13996. if (!uniform)
  13997. return;
  13998. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13999. };
  14000. /**
  14001. * Set the value of an uniform to a matrix (3x3)
  14002. * @param uniform defines the webGL uniform location where to store the value
  14003. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14004. */
  14005. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14006. if (!uniform)
  14007. return;
  14008. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14009. };
  14010. /**
  14011. * Set the value of an uniform to a matrix (2x2)
  14012. * @param uniform defines the webGL uniform location where to store the value
  14013. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14014. */
  14015. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14016. if (!uniform)
  14017. return;
  14018. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14019. };
  14020. /**
  14021. * Set the value of an uniform to a number (int)
  14022. * @param uniform defines the webGL uniform location where to store the value
  14023. * @param value defines the int number to store
  14024. */
  14025. Engine.prototype.setInt = function (uniform, value) {
  14026. if (!uniform)
  14027. return;
  14028. this._gl.uniform1i(uniform, value);
  14029. };
  14030. /**
  14031. * Set the value of an uniform to a number (float)
  14032. * @param uniform defines the webGL uniform location where to store the value
  14033. * @param value defines the float number to store
  14034. */
  14035. Engine.prototype.setFloat = function (uniform, value) {
  14036. if (!uniform)
  14037. return;
  14038. this._gl.uniform1f(uniform, value);
  14039. };
  14040. /**
  14041. * Set the value of an uniform to a vec2
  14042. * @param uniform defines the webGL uniform location where to store the value
  14043. * @param x defines the 1st component of the value
  14044. * @param y defines the 2nd component of the value
  14045. */
  14046. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14047. if (!uniform)
  14048. return;
  14049. this._gl.uniform2f(uniform, x, y);
  14050. };
  14051. /**
  14052. * Set the value of an uniform to a vec3
  14053. * @param uniform defines the webGL uniform location where to store the value
  14054. * @param x defines the 1st component of the value
  14055. * @param y defines the 2nd component of the value
  14056. * @param z defines the 3rd component of the value
  14057. */
  14058. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14059. if (!uniform)
  14060. return;
  14061. this._gl.uniform3f(uniform, x, y, z);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to a boolean
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param bool defines the boolean to store
  14067. */
  14068. Engine.prototype.setBool = function (uniform, bool) {
  14069. if (!uniform)
  14070. return;
  14071. this._gl.uniform1i(uniform, bool);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to a vec4
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param x defines the 1st component of the value
  14077. * @param y defines the 2nd component of the value
  14078. * @param z defines the 3rd component of the value
  14079. * @param w defines the 4th component of the value
  14080. */
  14081. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniform4f(uniform, x, y, z, w);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a Color3
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param color3 defines the color to store
  14090. */
  14091. Engine.prototype.setColor3 = function (uniform, color3) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to a Color3 and an alpha value
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param color3 defines the color to store
  14100. * @param alpha defines the alpha component to store
  14101. */
  14102. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14103. if (!uniform)
  14104. return;
  14105. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14106. };
  14107. /**
  14108. * Sets a Color4 on a uniform variable
  14109. * @param uniform defines the uniform location
  14110. * @param color4 defines the value to be set
  14111. */
  14112. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14113. if (!uniform)
  14114. return;
  14115. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14116. };
  14117. // States
  14118. /**
  14119. * Set various states to the webGL context
  14120. * @param culling defines backface culling state
  14121. * @param zOffset defines the value to apply to zOffset (0 by default)
  14122. * @param force defines if states must be applied even if cache is up to date
  14123. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14124. */
  14125. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14126. if (zOffset === void 0) { zOffset = 0; }
  14127. if (reverseSide === void 0) { reverseSide = false; }
  14128. // Culling
  14129. if (this._depthCullingState.cull !== culling || force) {
  14130. this._depthCullingState.cull = culling;
  14131. }
  14132. // Cull face
  14133. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14134. if (this._depthCullingState.cullFace !== cullFace || force) {
  14135. this._depthCullingState.cullFace = cullFace;
  14136. }
  14137. // Z offset
  14138. this.setZOffset(zOffset);
  14139. // Front face
  14140. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14141. if (this._depthCullingState.frontFace !== frontFace || force) {
  14142. this._depthCullingState.frontFace = frontFace;
  14143. }
  14144. };
  14145. /**
  14146. * Set the z offset to apply to current rendering
  14147. * @param value defines the offset to apply
  14148. */
  14149. Engine.prototype.setZOffset = function (value) {
  14150. this._depthCullingState.zOffset = value;
  14151. };
  14152. /**
  14153. * Gets the current value of the zOffset
  14154. * @returns the current zOffset state
  14155. */
  14156. Engine.prototype.getZOffset = function () {
  14157. return this._depthCullingState.zOffset;
  14158. };
  14159. /**
  14160. * Enable or disable depth buffering
  14161. * @param enable defines the state to set
  14162. */
  14163. Engine.prototype.setDepthBuffer = function (enable) {
  14164. this._depthCullingState.depthTest = enable;
  14165. };
  14166. /**
  14167. * Gets a boolean indicating if depth writing is enabled
  14168. * @returns the current depth writing state
  14169. */
  14170. Engine.prototype.getDepthWrite = function () {
  14171. return this._depthCullingState.depthMask;
  14172. };
  14173. /**
  14174. * Enable or disable depth writing
  14175. * @param enable defines the state to set
  14176. */
  14177. Engine.prototype.setDepthWrite = function (enable) {
  14178. this._depthCullingState.depthMask = enable;
  14179. };
  14180. /**
  14181. * Enable or disable color writing
  14182. * @param enable defines the state to set
  14183. */
  14184. Engine.prototype.setColorWrite = function (enable) {
  14185. this._gl.colorMask(enable, enable, enable, enable);
  14186. this._colorWrite = enable;
  14187. };
  14188. /**
  14189. * Gets a boolean indicating if color writing is enabled
  14190. * @returns the current color writing state
  14191. */
  14192. Engine.prototype.getColorWrite = function () {
  14193. return this._colorWrite;
  14194. };
  14195. /**
  14196. * Sets alpha constants used by some alpha blending modes
  14197. * @param r defines the red component
  14198. * @param g defines the green component
  14199. * @param b defines the blue component
  14200. * @param a defines the alpha component
  14201. */
  14202. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14203. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14204. };
  14205. /**
  14206. * Sets the current alpha mode
  14207. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14208. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14209. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14210. */
  14211. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14212. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14213. if (this._alphaMode === mode) {
  14214. return;
  14215. }
  14216. switch (mode) {
  14217. case Engine.ALPHA_DISABLE:
  14218. this._alphaState.alphaBlend = false;
  14219. break;
  14220. case Engine.ALPHA_PREMULTIPLIED:
  14221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14222. this._alphaState.alphaBlend = true;
  14223. break;
  14224. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14225. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14226. this._alphaState.alphaBlend = true;
  14227. break;
  14228. case Engine.ALPHA_COMBINE:
  14229. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14230. this._alphaState.alphaBlend = true;
  14231. break;
  14232. case Engine.ALPHA_ONEONE:
  14233. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14234. this._alphaState.alphaBlend = true;
  14235. break;
  14236. case Engine.ALPHA_ADD:
  14237. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14238. this._alphaState.alphaBlend = true;
  14239. break;
  14240. case Engine.ALPHA_SUBTRACT:
  14241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14242. this._alphaState.alphaBlend = true;
  14243. break;
  14244. case Engine.ALPHA_MULTIPLY:
  14245. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14246. this._alphaState.alphaBlend = true;
  14247. break;
  14248. case Engine.ALPHA_MAXIMIZED:
  14249. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14250. this._alphaState.alphaBlend = true;
  14251. break;
  14252. case Engine.ALPHA_INTERPOLATE:
  14253. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14254. this._alphaState.alphaBlend = true;
  14255. break;
  14256. case Engine.ALPHA_SCREENMODE:
  14257. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14258. this._alphaState.alphaBlend = true;
  14259. break;
  14260. }
  14261. if (!noDepthWriteChange) {
  14262. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14263. }
  14264. this._alphaMode = mode;
  14265. };
  14266. /**
  14267. * Gets the current alpha mode
  14268. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14269. * @returns the current alpha mode
  14270. */
  14271. Engine.prototype.getAlphaMode = function () {
  14272. return this._alphaMode;
  14273. };
  14274. // Textures
  14275. /**
  14276. * Force the entire cache to be cleared
  14277. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14278. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14279. */
  14280. Engine.prototype.wipeCaches = function (bruteForce) {
  14281. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14282. return;
  14283. }
  14284. this._currentEffect = null;
  14285. if (bruteForce) {
  14286. this.resetTextureCache();
  14287. this._currentProgram = null;
  14288. this._stencilState.reset();
  14289. this._depthCullingState.reset();
  14290. this.setDepthFunctionToLessOrEqual();
  14291. this._alphaState.reset();
  14292. }
  14293. this._resetVertexBufferBinding();
  14294. this._cachedIndexBuffer = null;
  14295. this._cachedEffectForVertexBuffers = null;
  14296. this._unbindVertexArrayObject();
  14297. this.bindIndexBuffer(null);
  14298. };
  14299. /**
  14300. * Set the compressed texture format to use, based on the formats you have, and the formats
  14301. * supported by the hardware / browser.
  14302. *
  14303. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14304. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14305. * to API arguments needed to compressed textures. This puts the burden on the container
  14306. * generator to house the arcane code for determining these for current & future formats.
  14307. *
  14308. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14309. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14310. *
  14311. * Note: The result of this call is not taken into account when a texture is base64.
  14312. *
  14313. * @param formatsAvailable defines the list of those format families you have created
  14314. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14315. *
  14316. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14317. * @returns The extension selected.
  14318. */
  14319. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14320. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14321. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14322. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14323. return this._textureFormatInUse = this._texturesSupported[i];
  14324. }
  14325. }
  14326. }
  14327. // actively set format to nothing, to allow this to be called more than once
  14328. // and possibly fail the 2nd time
  14329. this._textureFormatInUse = null;
  14330. return null;
  14331. };
  14332. /** @ignore */
  14333. Engine.prototype._createTexture = function () {
  14334. var texture = this._gl.createTexture();
  14335. if (!texture) {
  14336. throw new Error("Unable to create texture");
  14337. }
  14338. return texture;
  14339. };
  14340. /**
  14341. * Usually called from BABYLON.Texture.ts.
  14342. * Passed information to create a WebGLTexture
  14343. * @param urlArg defines a value which contains one of the following:
  14344. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14345. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14346. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14347. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14348. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14349. * @param scene needed for loading to the correct scene
  14350. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14351. * @param onLoad optional callback to be called upon successful completion
  14352. * @param onError optional callback to be called upon failure
  14353. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14354. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14355. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14356. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14357. */
  14358. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14359. var _this = this;
  14360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14361. if (onLoad === void 0) { onLoad = null; }
  14362. if (onError === void 0) { onError = null; }
  14363. if (buffer === void 0) { buffer = null; }
  14364. if (fallback === void 0) { fallback = null; }
  14365. if (format === void 0) { format = null; }
  14366. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14367. var fromData = url.substr(0, 5) === "data:";
  14368. var fromBlob = url.substr(0, 5) === "blob:";
  14369. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14370. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14371. // establish the file extension, if possible
  14372. var lastDot = url.lastIndexOf('.');
  14373. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14374. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14375. var isTGA = (extension.indexOf(".tga") === 0);
  14376. // determine if a ktx file should be substituted
  14377. var isKTX = false;
  14378. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14379. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14380. isKTX = true;
  14381. }
  14382. if (scene) {
  14383. scene._addPendingData(texture);
  14384. }
  14385. texture.url = url;
  14386. texture.generateMipMaps = !noMipmap;
  14387. texture.samplingMode = samplingMode;
  14388. texture.invertY = invertY;
  14389. if (!this._doNotHandleContextLost) {
  14390. // Keep a link to the buffer only if we plan to handle context lost
  14391. texture._buffer = buffer;
  14392. }
  14393. var onLoadObserver = null;
  14394. if (onLoad && !fallback) {
  14395. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14396. }
  14397. if (!fallback)
  14398. this._internalTexturesCache.push(texture);
  14399. var onerror = function (message, exception) {
  14400. if (scene) {
  14401. scene._removePendingData(texture);
  14402. }
  14403. if (onLoadObserver) {
  14404. texture.onLoadedObservable.remove(onLoadObserver);
  14405. }
  14406. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14407. if (isKTX) {
  14408. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14409. }
  14410. else if (BABYLON.Tools.UseFallbackTexture) {
  14411. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14412. }
  14413. if (onError) {
  14414. onError(message || "Unknown error", exception);
  14415. }
  14416. };
  14417. var callback = null;
  14418. // processing for non-image formats
  14419. if (isKTX || isTGA || isDDS) {
  14420. if (isKTX) {
  14421. callback = function (data) {
  14422. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14423. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14424. ktx.uploadLevels(_this._gl, !noMipmap);
  14425. return false;
  14426. }, samplingMode);
  14427. };
  14428. }
  14429. else if (isTGA) {
  14430. callback = function (arrayBuffer) {
  14431. var data = new Uint8Array(arrayBuffer);
  14432. var header = BABYLON.TGATools.GetTGAHeader(data);
  14433. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14434. BABYLON.TGATools.UploadContent(_this._gl, data);
  14435. return false;
  14436. }, samplingMode);
  14437. };
  14438. }
  14439. else if (isDDS) {
  14440. callback = function (data) {
  14441. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14442. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14443. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14444. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14445. return false;
  14446. }, samplingMode);
  14447. };
  14448. }
  14449. if (!buffer) {
  14450. this._loadFile(url, function (data) {
  14451. if (callback) {
  14452. callback(data);
  14453. }
  14454. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14455. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14456. });
  14457. }
  14458. else {
  14459. if (callback) {
  14460. callback(buffer);
  14461. }
  14462. }
  14463. // image format processing
  14464. }
  14465. else {
  14466. var onload = function (img) {
  14467. if (fromBlob && !_this._doNotHandleContextLost) {
  14468. // We need to store the image if we need to rebuild the texture
  14469. // in case of a webgl context lost
  14470. texture._buffer = img;
  14471. }
  14472. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14473. var gl = _this._gl;
  14474. var isPot = (img.width === potWidth && img.height === potHeight);
  14475. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14476. if (isPot) {
  14477. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14478. return false;
  14479. }
  14480. // Using shaders to rescale because canvas.drawImage is lossy
  14481. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14482. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14483. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14487. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14488. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14489. _this._releaseTexture(source);
  14490. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14491. continuationCallback();
  14492. });
  14493. return true;
  14494. }, samplingMode);
  14495. };
  14496. if (!fromData || isBase64)
  14497. if (buffer instanceof HTMLImageElement) {
  14498. onload(buffer);
  14499. }
  14500. else {
  14501. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14502. }
  14503. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14504. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14505. else
  14506. onload(buffer);
  14507. }
  14508. return texture;
  14509. };
  14510. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14511. var _this = this;
  14512. var rtt = this.createRenderTargetTexture({
  14513. width: destination.width,
  14514. height: destination.height,
  14515. }, {
  14516. generateMipMaps: false,
  14517. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14518. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14519. generateDepthBuffer: false,
  14520. generateStencilBuffer: false
  14521. });
  14522. if (!this._rescalePostProcess) {
  14523. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14524. }
  14525. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14526. _this._rescalePostProcess.onApply = function (effect) {
  14527. effect._bindTexture("textureSampler", source);
  14528. };
  14529. var hostingScene = scene;
  14530. if (!hostingScene) {
  14531. hostingScene = _this.scenes[_this.scenes.length - 1];
  14532. }
  14533. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14534. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14535. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14536. _this.unBindFramebuffer(rtt);
  14537. _this._releaseTexture(rtt);
  14538. if (onComplete) {
  14539. onComplete();
  14540. }
  14541. });
  14542. };
  14543. /**
  14544. * Update a raw texture
  14545. * @param texture defines the texture to update
  14546. * @param data defines the data to store in the texture
  14547. * @param format defines the format of the data
  14548. * @param invertY defines if data must be stored with Y axis inverted
  14549. * @param compression defines the compression used (null by default)
  14550. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14551. */
  14552. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14553. if (compression === void 0) { compression = null; }
  14554. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14555. if (!texture) {
  14556. return;
  14557. }
  14558. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14559. var internalFormat = this._getInternalFormat(format);
  14560. var textureType = this._getWebGLTextureType(type);
  14561. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14562. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14563. if (!this._doNotHandleContextLost) {
  14564. texture._bufferView = data;
  14565. texture.format = format;
  14566. texture.type = type;
  14567. texture.invertY = invertY;
  14568. texture._compression = compression;
  14569. }
  14570. if (texture.width % 4 !== 0) {
  14571. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14572. }
  14573. if (compression && data) {
  14574. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14575. }
  14576. else {
  14577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14578. }
  14579. if (texture.generateMipMaps) {
  14580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14581. }
  14582. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14583. // this.resetTextureCache();
  14584. texture.isReady = true;
  14585. };
  14586. /**
  14587. * Creates a raw texture
  14588. * @param data defines the data to store in the texture
  14589. * @param width defines the width of the texture
  14590. * @param height defines the height of the texture
  14591. * @param format defines the format of the data
  14592. * @param generateMipMaps defines if the engine should generate the mip levels
  14593. * @param invertY defines if data must be stored with Y axis inverted
  14594. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14595. * @param compression defines the compression used (null by default)
  14596. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14597. * @returns the raw texture inside an InternalTexture
  14598. */
  14599. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14600. if (compression === void 0) { compression = null; }
  14601. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14603. texture.baseWidth = width;
  14604. texture.baseHeight = height;
  14605. texture.width = width;
  14606. texture.height = height;
  14607. texture.format = format;
  14608. texture.generateMipMaps = generateMipMaps;
  14609. texture.samplingMode = samplingMode;
  14610. texture.invertY = invertY;
  14611. texture._compression = compression;
  14612. texture.type = type;
  14613. if (!this._doNotHandleContextLost) {
  14614. texture._bufferView = data;
  14615. }
  14616. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14617. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14618. // Filters
  14619. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14622. if (generateMipMaps) {
  14623. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14624. }
  14625. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14626. this._internalTexturesCache.push(texture);
  14627. return texture;
  14628. };
  14629. /**
  14630. * Creates a dynamic texture
  14631. * @param width defines the width of the texture
  14632. * @param height defines the height of the texture
  14633. * @param generateMipMaps defines if the engine should generate the mip levels
  14634. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14635. * @returns the dynamic texture inside an InternalTexture
  14636. */
  14637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14639. texture.baseWidth = width;
  14640. texture.baseHeight = height;
  14641. if (generateMipMaps) {
  14642. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14643. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14644. }
  14645. // this.resetTextureCache();
  14646. texture.width = width;
  14647. texture.height = height;
  14648. texture.isReady = false;
  14649. texture.generateMipMaps = generateMipMaps;
  14650. texture.samplingMode = samplingMode;
  14651. this.updateTextureSamplingMode(samplingMode, texture);
  14652. this._internalTexturesCache.push(texture);
  14653. return texture;
  14654. };
  14655. /**
  14656. * Update the sampling mode of a given texture
  14657. * @param samplingMode defines the required sampling mode
  14658. * @param texture defines the texture to update
  14659. */
  14660. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14661. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14662. if (texture.isCube) {
  14663. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14664. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14665. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14666. }
  14667. else if (texture.is3D) {
  14668. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14669. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14670. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14671. }
  14672. else {
  14673. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14674. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14675. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14676. }
  14677. texture.samplingMode = samplingMode;
  14678. };
  14679. /**
  14680. * Update the content of a dynamic texture
  14681. * @param texture defines the texture to update
  14682. * @param canvas defines the canvas containing the source
  14683. * @param invertY defines if data must be stored with Y axis inverted
  14684. * @param premulAlpha defines if alpha is stored as premultiplied
  14685. * @param format defines the format of the data
  14686. */
  14687. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14688. if (premulAlpha === void 0) { premulAlpha = false; }
  14689. if (!texture) {
  14690. return;
  14691. }
  14692. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14693. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14694. if (premulAlpha) {
  14695. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14696. }
  14697. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14698. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14699. if (texture.generateMipMaps) {
  14700. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14701. }
  14702. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14703. if (premulAlpha) {
  14704. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14705. }
  14706. texture.isReady = true;
  14707. };
  14708. /**
  14709. * Update a video texture
  14710. * @param texture defines the texture to update
  14711. * @param video defines the video element to use
  14712. * @param invertY defines if data must be stored with Y axis inverted
  14713. */
  14714. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14715. if (!texture || texture._isDisabled) {
  14716. return;
  14717. }
  14718. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14719. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14720. try {
  14721. // Testing video texture support
  14722. if (this._videoTextureSupported === undefined) {
  14723. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14724. if (this._gl.getError() !== 0) {
  14725. this._videoTextureSupported = false;
  14726. }
  14727. else {
  14728. this._videoTextureSupported = true;
  14729. }
  14730. }
  14731. // Copy video through the current working canvas if video texture is not supported
  14732. if (!this._videoTextureSupported) {
  14733. if (!texture._workingCanvas) {
  14734. texture._workingCanvas = document.createElement("canvas");
  14735. var context = texture._workingCanvas.getContext("2d");
  14736. if (!context) {
  14737. throw new Error("Unable to get 2d context");
  14738. }
  14739. texture._workingContext = context;
  14740. texture._workingCanvas.width = texture.width;
  14741. texture._workingCanvas.height = texture.height;
  14742. }
  14743. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14744. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14745. }
  14746. else {
  14747. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14748. }
  14749. if (texture.generateMipMaps) {
  14750. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14751. }
  14752. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14753. // this.resetTextureCache();
  14754. texture.isReady = true;
  14755. }
  14756. catch (ex) {
  14757. // Something unexpected
  14758. // Let's disable the texture
  14759. texture._isDisabled = true;
  14760. }
  14761. };
  14762. /**
  14763. * Updates a depth texture Comparison Mode and Function.
  14764. * If the comparison Function is equal to 0, the mode will be set to none.
  14765. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14766. * @param texture The texture to set the comparison function for
  14767. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14768. */
  14769. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14770. if (this.webGLVersion === 1) {
  14771. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14772. return;
  14773. }
  14774. var gl = this._gl;
  14775. if (texture.isCube) {
  14776. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14777. if (comparisonFunction === 0) {
  14778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14780. }
  14781. else {
  14782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14784. }
  14785. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14786. }
  14787. else {
  14788. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14789. if (comparisonFunction === 0) {
  14790. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14791. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14792. }
  14793. else {
  14794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14796. }
  14797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14798. }
  14799. texture._comparisonFunction = comparisonFunction;
  14800. };
  14801. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14802. var width = size.width || size;
  14803. var height = size.height || size;
  14804. internalTexture.baseWidth = width;
  14805. internalTexture.baseHeight = height;
  14806. internalTexture.width = width;
  14807. internalTexture.height = height;
  14808. internalTexture.isReady = true;
  14809. internalTexture.samples = 1;
  14810. internalTexture.generateMipMaps = false;
  14811. internalTexture._generateDepthBuffer = true;
  14812. internalTexture._generateStencilBuffer = generateStencil;
  14813. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14814. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14815. internalTexture._comparisonFunction = comparisonFunction;
  14816. var gl = this._gl;
  14817. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14818. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14819. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14820. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14821. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14822. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14823. if (comparisonFunction === 0) {
  14824. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14825. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14826. }
  14827. else {
  14828. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14829. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14830. }
  14831. };
  14832. /**
  14833. * Creates a depth stencil texture.
  14834. * This is only available in WebGL 2 or with the depth texture extension available.
  14835. * @param size The size of face edge in the texture.
  14836. * @param options The options defining the texture.
  14837. * @returns The texture
  14838. */
  14839. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14840. if (options.isCube) {
  14841. var width = size.width || size;
  14842. return this._createDepthStencilCubeTexture(width, options);
  14843. }
  14844. else {
  14845. return this._createDepthStencilTexture(size, options);
  14846. }
  14847. };
  14848. /**
  14849. * Creates a depth stencil texture.
  14850. * This is only available in WebGL 2 or with the depth texture extension available.
  14851. * @param size The size of face edge in the texture.
  14852. * @param options The options defining the texture.
  14853. * @returns The texture
  14854. */
  14855. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14856. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14857. if (!this._caps.depthTextureExtension) {
  14858. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14859. return internalTexture;
  14860. }
  14861. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14862. var gl = this._gl;
  14863. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14864. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14865. if (this.webGLVersion > 1) {
  14866. if (internalOptions.generateStencil) {
  14867. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14868. }
  14869. else {
  14870. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14871. }
  14872. }
  14873. else {
  14874. if (internalOptions.generateStencil) {
  14875. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14876. }
  14877. else {
  14878. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14879. }
  14880. }
  14881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14882. return internalTexture;
  14883. };
  14884. /**
  14885. * Creates a depth stencil cube texture.
  14886. * This is only available in WebGL 2.
  14887. * @param size The size of face edge in the cube texture.
  14888. * @param options The options defining the cube texture.
  14889. * @returns The cube texture
  14890. */
  14891. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14892. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14893. internalTexture.isCube = true;
  14894. if (this.webGLVersion === 1) {
  14895. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14896. return internalTexture;
  14897. }
  14898. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14899. var gl = this._gl;
  14900. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14901. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14902. // Create the depth/stencil buffer
  14903. for (var face = 0; face < 6; face++) {
  14904. if (internalOptions.generateStencil) {
  14905. 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);
  14906. }
  14907. else {
  14908. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14909. }
  14910. }
  14911. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14912. return internalTexture;
  14913. };
  14914. /**
  14915. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14916. * @param renderTarget The render target to set the frame buffer for
  14917. */
  14918. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14919. // Create the framebuffer
  14920. var internalTexture = renderTarget.getInternalTexture();
  14921. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14922. return;
  14923. }
  14924. var gl = this._gl;
  14925. var depthStencilTexture = renderTarget.depthStencilTexture;
  14926. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14927. if (depthStencilTexture.isCube) {
  14928. if (depthStencilTexture._generateStencilBuffer) {
  14929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14930. }
  14931. else {
  14932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14933. }
  14934. }
  14935. else {
  14936. if (depthStencilTexture._generateStencilBuffer) {
  14937. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14938. }
  14939. else {
  14940. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14941. }
  14942. }
  14943. this.bindUnboundFramebuffer(null);
  14944. };
  14945. /**
  14946. * Creates a new render target texture
  14947. * @param size defines the size of the texture
  14948. * @param options defines the options used to create the texture
  14949. * @returns a new render target texture stored in an InternalTexture
  14950. */
  14951. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14952. var fullOptions = new RenderTargetCreationOptions();
  14953. if (options !== undefined && typeof options === "object") {
  14954. fullOptions.generateMipMaps = options.generateMipMaps;
  14955. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14956. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14957. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14958. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14959. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14960. }
  14961. else {
  14962. fullOptions.generateMipMaps = options;
  14963. fullOptions.generateDepthBuffer = true;
  14964. fullOptions.generateStencilBuffer = false;
  14965. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14966. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14967. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14968. }
  14969. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14970. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14971. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14972. }
  14973. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14974. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14975. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14976. }
  14977. var gl = this._gl;
  14978. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14979. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14980. var width = size.width || size;
  14981. var height = size.height || size;
  14982. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14983. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14984. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14985. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14986. }
  14987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14991. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14992. // Create the framebuffer
  14993. var framebuffer = gl.createFramebuffer();
  14994. this.bindUnboundFramebuffer(framebuffer);
  14995. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14996. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14997. if (fullOptions.generateMipMaps) {
  14998. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14999. }
  15000. // Unbind
  15001. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15002. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15003. this.bindUnboundFramebuffer(null);
  15004. texture._framebuffer = framebuffer;
  15005. texture.baseWidth = width;
  15006. texture.baseHeight = height;
  15007. texture.width = width;
  15008. texture.height = height;
  15009. texture.isReady = true;
  15010. texture.samples = 1;
  15011. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15012. texture.samplingMode = fullOptions.samplingMode;
  15013. texture.type = fullOptions.type;
  15014. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15015. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15016. // this.resetTextureCache();
  15017. this._internalTexturesCache.push(texture);
  15018. return texture;
  15019. };
  15020. /**
  15021. * Create a multi render target texture
  15022. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15023. * @param size defines the size of the texture
  15024. * @param options defines the creation options
  15025. * @returns the cube texture as an InternalTexture
  15026. */
  15027. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15028. var generateMipMaps = false;
  15029. var generateDepthBuffer = true;
  15030. var generateStencilBuffer = false;
  15031. var generateDepthTexture = false;
  15032. var textureCount = 1;
  15033. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15034. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15035. var types = new Array();
  15036. var samplingModes = new Array();
  15037. if (options !== undefined) {
  15038. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15039. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15040. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15041. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15042. textureCount = options.textureCount || 1;
  15043. if (options.types) {
  15044. types = options.types;
  15045. }
  15046. if (options.samplingModes) {
  15047. samplingModes = options.samplingModes;
  15048. }
  15049. }
  15050. var gl = this._gl;
  15051. // Create the framebuffer
  15052. var framebuffer = gl.createFramebuffer();
  15053. this.bindUnboundFramebuffer(framebuffer);
  15054. var width = size.width || size;
  15055. var height = size.height || size;
  15056. var textures = [];
  15057. var attachments = [];
  15058. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15059. for (var i = 0; i < textureCount; i++) {
  15060. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15061. var type = types[i] || defaultType;
  15062. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15063. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15064. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15065. }
  15066. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15067. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15068. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15069. }
  15070. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15071. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15072. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15073. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15074. }
  15075. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15076. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15077. textures.push(texture);
  15078. attachments.push(attachment);
  15079. gl.activeTexture(gl["TEXTURE" + i]);
  15080. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15085. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15086. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15087. if (generateMipMaps) {
  15088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15089. }
  15090. // Unbind
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15092. texture._framebuffer = framebuffer;
  15093. texture._depthStencilBuffer = depthStencilBuffer;
  15094. texture.baseWidth = width;
  15095. texture.baseHeight = height;
  15096. texture.width = width;
  15097. texture.height = height;
  15098. texture.isReady = true;
  15099. texture.samples = 1;
  15100. texture.generateMipMaps = generateMipMaps;
  15101. texture.samplingMode = samplingMode;
  15102. texture.type = type;
  15103. texture._generateDepthBuffer = generateDepthBuffer;
  15104. texture._generateStencilBuffer = generateStencilBuffer;
  15105. texture._attachments = attachments;
  15106. this._internalTexturesCache.push(texture);
  15107. }
  15108. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15109. // Depth texture
  15110. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15111. gl.activeTexture(gl.TEXTURE0);
  15112. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15114. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15116. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15117. 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);
  15118. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15119. depthTexture._framebuffer = framebuffer;
  15120. depthTexture.baseWidth = width;
  15121. depthTexture.baseHeight = height;
  15122. depthTexture.width = width;
  15123. depthTexture.height = height;
  15124. depthTexture.isReady = true;
  15125. depthTexture.samples = 1;
  15126. depthTexture.generateMipMaps = generateMipMaps;
  15127. depthTexture.samplingMode = gl.NEAREST;
  15128. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15129. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15130. textures.push(depthTexture);
  15131. this._internalTexturesCache.push(depthTexture);
  15132. }
  15133. gl.drawBuffers(attachments);
  15134. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15135. this.bindUnboundFramebuffer(null);
  15136. this.resetTextureCache();
  15137. return textures;
  15138. };
  15139. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15140. if (samples === void 0) { samples = 1; }
  15141. var depthStencilBuffer = null;
  15142. var gl = this._gl;
  15143. // Create the depth/stencil buffer
  15144. if (generateStencilBuffer) {
  15145. depthStencilBuffer = gl.createRenderbuffer();
  15146. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15147. if (samples > 1) {
  15148. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15149. }
  15150. else {
  15151. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15152. }
  15153. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15154. }
  15155. else if (generateDepthBuffer) {
  15156. depthStencilBuffer = gl.createRenderbuffer();
  15157. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15158. if (samples > 1) {
  15159. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15160. }
  15161. else {
  15162. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15163. }
  15164. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15165. }
  15166. return depthStencilBuffer;
  15167. };
  15168. /**
  15169. * Updates the sample count of a render target texture
  15170. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15171. * @param texture defines the texture to update
  15172. * @param samples defines the sample count to set
  15173. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15174. */
  15175. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15176. if (this.webGLVersion < 2 || !texture) {
  15177. return 1;
  15178. }
  15179. if (texture.samples === samples) {
  15180. return samples;
  15181. }
  15182. var gl = this._gl;
  15183. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15184. // Dispose previous render buffers
  15185. if (texture._depthStencilBuffer) {
  15186. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15187. texture._depthStencilBuffer = null;
  15188. }
  15189. if (texture._MSAAFramebuffer) {
  15190. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15191. texture._MSAAFramebuffer = null;
  15192. }
  15193. if (texture._MSAARenderBuffer) {
  15194. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15195. texture._MSAARenderBuffer = null;
  15196. }
  15197. if (samples > 1) {
  15198. var framebuffer = gl.createFramebuffer();
  15199. if (!framebuffer) {
  15200. throw new Error("Unable to create multi sampled framebuffer");
  15201. }
  15202. texture._MSAAFramebuffer = framebuffer;
  15203. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15204. var colorRenderbuffer = gl.createRenderbuffer();
  15205. if (!colorRenderbuffer) {
  15206. throw new Error("Unable to create multi sampled framebuffer");
  15207. }
  15208. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15209. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15210. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15211. texture._MSAARenderBuffer = colorRenderbuffer;
  15212. }
  15213. else {
  15214. this.bindUnboundFramebuffer(texture._framebuffer);
  15215. }
  15216. texture.samples = samples;
  15217. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15218. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15219. this.bindUnboundFramebuffer(null);
  15220. return samples;
  15221. };
  15222. /**
  15223. * Update the sample count for a given multiple render target texture
  15224. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15225. * @param textures defines the textures to update
  15226. * @param samples defines the sample count to set
  15227. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15228. */
  15229. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15230. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15231. return 1;
  15232. }
  15233. if (textures[0].samples === samples) {
  15234. return samples;
  15235. }
  15236. var gl = this._gl;
  15237. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15238. // Dispose previous render buffers
  15239. if (textures[0]._depthStencilBuffer) {
  15240. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15241. textures[0]._depthStencilBuffer = null;
  15242. }
  15243. if (textures[0]._MSAAFramebuffer) {
  15244. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15245. textures[0]._MSAAFramebuffer = null;
  15246. }
  15247. for (var i = 0; i < textures.length; i++) {
  15248. if (textures[i]._MSAARenderBuffer) {
  15249. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15250. textures[i]._MSAARenderBuffer = null;
  15251. }
  15252. }
  15253. if (samples > 1) {
  15254. var framebuffer = gl.createFramebuffer();
  15255. if (!framebuffer) {
  15256. throw new Error("Unable to create multi sampled framebuffer");
  15257. }
  15258. this.bindUnboundFramebuffer(framebuffer);
  15259. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15260. var attachments = [];
  15261. for (var i = 0; i < textures.length; i++) {
  15262. var texture = textures[i];
  15263. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15264. var colorRenderbuffer = gl.createRenderbuffer();
  15265. if (!colorRenderbuffer) {
  15266. throw new Error("Unable to create multi sampled framebuffer");
  15267. }
  15268. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15269. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15271. texture._MSAAFramebuffer = framebuffer;
  15272. texture._MSAARenderBuffer = colorRenderbuffer;
  15273. texture.samples = samples;
  15274. texture._depthStencilBuffer = depthStencilBuffer;
  15275. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15276. attachments.push(attachment);
  15277. }
  15278. gl.drawBuffers(attachments);
  15279. }
  15280. else {
  15281. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15282. }
  15283. this.bindUnboundFramebuffer(null);
  15284. return samples;
  15285. };
  15286. /** @ignore */
  15287. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15288. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15289. };
  15290. /** @ignore */
  15291. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15292. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15293. };
  15294. /**
  15295. * Creates a new render target cube texture
  15296. * @param size defines the size of the texture
  15297. * @param options defines the options used to create the texture
  15298. * @returns a new render target cube texture stored in an InternalTexture
  15299. */
  15300. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15301. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15302. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15303. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15304. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15305. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15306. }
  15307. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15308. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15309. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15310. }
  15311. var gl = this._gl;
  15312. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15313. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15314. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15315. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15316. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15317. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15318. }
  15319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15323. for (var face = 0; face < 6; face++) {
  15324. 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);
  15325. }
  15326. // Create the framebuffer
  15327. var framebuffer = gl.createFramebuffer();
  15328. this.bindUnboundFramebuffer(framebuffer);
  15329. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15330. // MipMaps
  15331. if (fullOptions.generateMipMaps) {
  15332. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15333. }
  15334. // Unbind
  15335. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15336. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15337. this.bindUnboundFramebuffer(null);
  15338. texture._framebuffer = framebuffer;
  15339. texture.width = size;
  15340. texture.height = size;
  15341. texture.isReady = true;
  15342. texture.isCube = true;
  15343. texture.samples = 1;
  15344. texture.generateMipMaps = fullOptions.generateMipMaps;
  15345. texture.samplingMode = fullOptions.samplingMode;
  15346. texture.type = fullOptions.type;
  15347. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15348. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15349. this._internalTexturesCache.push(texture);
  15350. return texture;
  15351. };
  15352. /**
  15353. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15354. * @param rootUrl defines the url where the file to load is located
  15355. * @param scene defines the current scene
  15356. * @param scale defines scale to apply to the mip map selection
  15357. * @param offset defines offset to apply to the mip map selection
  15358. * @param onLoad defines an optional callback raised when the texture is loaded
  15359. * @param onError defines an optional callback raised if there is an issue to load the texture
  15360. * @param format defines the format of the data
  15361. * @param forcedExtension defines the extension to use to pick the right loader
  15362. * @returns the cube texture as an InternalTexture
  15363. */
  15364. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15365. var _this = this;
  15366. if (onLoad === void 0) { onLoad = null; }
  15367. if (onError === void 0) { onError = null; }
  15368. if (forcedExtension === void 0) { forcedExtension = null; }
  15369. var callback = function (loadData) {
  15370. if (!loadData) {
  15371. if (onLoad) {
  15372. onLoad(null);
  15373. }
  15374. return;
  15375. }
  15376. var texture = loadData.texture;
  15377. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15378. texture._lodGenerationScale = scale;
  15379. texture._lodGenerationOffset = offset;
  15380. if (_this._caps.textureLOD) {
  15381. // Do not add extra process if texture lod is supported.
  15382. if (onLoad) {
  15383. onLoad(texture);
  15384. }
  15385. return;
  15386. }
  15387. var mipSlices = 3;
  15388. var gl = _this._gl;
  15389. var width = loadData.width;
  15390. if (!width) {
  15391. return;
  15392. }
  15393. var textures = [];
  15394. for (var i = 0; i < mipSlices; i++) {
  15395. //compute LOD from even spacing in smoothness (matching shader calculation)
  15396. var smoothness = i / (mipSlices - 1);
  15397. var roughness = 1 - smoothness;
  15398. var minLODIndex = offset; // roughness = 0
  15399. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15400. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15401. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15402. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15403. glTextureFromLod.isCube = true;
  15404. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15409. if (loadData.isDDS) {
  15410. var info = loadData.info;
  15411. var data = loadData.data;
  15412. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15413. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15414. }
  15415. else {
  15416. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15417. }
  15418. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15419. // Wrap in a base texture for easy binding.
  15420. var lodTexture = new BABYLON.BaseTexture(scene);
  15421. lodTexture.isCube = true;
  15422. lodTexture._texture = glTextureFromLod;
  15423. glTextureFromLod.isReady = true;
  15424. textures.push(lodTexture);
  15425. }
  15426. texture._lodTextureHigh = textures[2];
  15427. texture._lodTextureMid = textures[1];
  15428. texture._lodTextureLow = textures[0];
  15429. if (onLoad) {
  15430. onLoad(texture);
  15431. }
  15432. };
  15433. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15434. };
  15435. /**
  15436. * Creates a cube texture
  15437. * @param rootUrl defines the url where the files to load is located
  15438. * @param scene defines the current scene
  15439. * @param files defines the list of files to load (1 per face)
  15440. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15441. * @param onLoad defines an optional callback raised when the texture is loaded
  15442. * @param onError defines an optional callback raised if there is an issue to load the texture
  15443. * @param format defines the format of the data
  15444. * @param forcedExtension defines the extension to use to pick the right loader
  15445. * @returns the cube texture as an InternalTexture
  15446. */
  15447. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15448. var _this = this;
  15449. if (onLoad === void 0) { onLoad = null; }
  15450. if (onError === void 0) { onError = null; }
  15451. if (forcedExtension === void 0) { forcedExtension = null; }
  15452. var gl = this._gl;
  15453. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15454. texture.isCube = true;
  15455. texture.url = rootUrl;
  15456. texture.generateMipMaps = !noMipmap;
  15457. if (!this._doNotHandleContextLost) {
  15458. texture._extension = forcedExtension;
  15459. texture._files = files;
  15460. }
  15461. var isKTX = false;
  15462. var isDDS = false;
  15463. var lastDot = rootUrl.lastIndexOf('.');
  15464. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15465. if (this._textureFormatInUse) {
  15466. extension = this._textureFormatInUse;
  15467. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15468. isKTX = true;
  15469. }
  15470. else {
  15471. isDDS = (extension === ".dds");
  15472. }
  15473. var onerror = function (request, exception) {
  15474. if (onError && request) {
  15475. onError(request.status + " " + request.statusText, exception);
  15476. }
  15477. };
  15478. if (isKTX) {
  15479. this._loadFile(rootUrl, function (data) {
  15480. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15481. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15482. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15483. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15484. ktx.uploadLevels(_this._gl, !noMipmap);
  15485. _this.setCubeMapTextureParams(gl, loadMipmap);
  15486. texture.width = ktx.pixelWidth;
  15487. texture.height = ktx.pixelHeight;
  15488. texture.isReady = true;
  15489. }, undefined, undefined, true, onerror);
  15490. }
  15491. else if (isDDS) {
  15492. if (files && files.length === 6) {
  15493. this._cascadeLoadFiles(scene, function (imgs) {
  15494. var info;
  15495. var loadMipmap = false;
  15496. var width = 0;
  15497. for (var index = 0; index < imgs.length; index++) {
  15498. var data = imgs[index];
  15499. info = BABYLON.DDSTools.GetDDSInfo(data);
  15500. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15501. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15502. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15503. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15504. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15505. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15506. }
  15507. texture.width = info.width;
  15508. texture.height = info.height;
  15509. texture.type = info.textureType;
  15510. width = info.width;
  15511. }
  15512. _this.setCubeMapTextureParams(gl, loadMipmap);
  15513. texture.isReady = true;
  15514. if (onLoad) {
  15515. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15516. }
  15517. }, files, onError);
  15518. }
  15519. else {
  15520. this._loadFile(rootUrl, function (data) {
  15521. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15522. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15523. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15524. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15525. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15526. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15527. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15528. }
  15529. _this.setCubeMapTextureParams(gl, loadMipmap);
  15530. texture.width = info.width;
  15531. texture.height = info.height;
  15532. texture.isReady = true;
  15533. texture.type = info.textureType;
  15534. if (onLoad) {
  15535. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15536. }
  15537. }, undefined, undefined, true, onerror);
  15538. }
  15539. }
  15540. else {
  15541. if (!files) {
  15542. throw new Error("Cannot load cubemap because files were not defined");
  15543. }
  15544. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15545. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15546. var height = width;
  15547. _this._prepareWorkingCanvas();
  15548. if (!_this._workingCanvas || !_this._workingContext) {
  15549. return;
  15550. }
  15551. _this._workingCanvas.width = width;
  15552. _this._workingCanvas.height = height;
  15553. var faces = [
  15554. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15555. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15556. ];
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15558. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15559. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15560. for (var index = 0; index < faces.length; index++) {
  15561. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15562. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15563. }
  15564. if (!noMipmap) {
  15565. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15566. }
  15567. _this.setCubeMapTextureParams(gl, !noMipmap);
  15568. texture.width = width;
  15569. texture.height = height;
  15570. texture.isReady = true;
  15571. if (format) {
  15572. texture.format = format;
  15573. }
  15574. texture.onLoadedObservable.notifyObservers(texture);
  15575. texture.onLoadedObservable.clear();
  15576. if (onLoad) {
  15577. onLoad();
  15578. }
  15579. }, files, onError);
  15580. }
  15581. this._internalTexturesCache.push(texture);
  15582. return texture;
  15583. };
  15584. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15589. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15590. // this.resetTextureCache();
  15591. };
  15592. /**
  15593. * Update a raw cube texture
  15594. * @param texture defines the texture to udpdate
  15595. * @param data defines the data to store
  15596. * @param format defines the data format
  15597. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15598. * @param invertY defines if data must be stored with Y axis inverted
  15599. * @param compression defines the compression used (null by default)
  15600. * @param level defines which level of the texture to update
  15601. */
  15602. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15603. if (compression === void 0) { compression = null; }
  15604. if (level === void 0) { level = 0; }
  15605. texture._bufferViewArray = data;
  15606. texture.format = format;
  15607. texture.type = type;
  15608. texture.invertY = invertY;
  15609. texture._compression = compression;
  15610. var gl = this._gl;
  15611. var textureType = this._getWebGLTextureType(type);
  15612. var internalFormat = this._getInternalFormat(format);
  15613. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15614. var needConversion = false;
  15615. if (internalFormat === gl.RGB) {
  15616. internalFormat = gl.RGBA;
  15617. needConversion = true;
  15618. }
  15619. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15620. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15621. if (texture.width % 4 !== 0) {
  15622. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15623. }
  15624. // Data are known to be in +X +Y +Z -X -Y -Z
  15625. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15626. var faceData = data[faceIndex];
  15627. if (compression) {
  15628. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15629. }
  15630. else {
  15631. if (needConversion) {
  15632. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15633. }
  15634. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15635. }
  15636. }
  15637. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15638. if (isPot && texture.generateMipMaps && level === 0) {
  15639. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15640. }
  15641. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15642. // this.resetTextureCache();
  15643. texture.isReady = true;
  15644. };
  15645. /**
  15646. * Creates a new raw cube texture
  15647. * @param data defines the array of data to use to create each face
  15648. * @param size defines the size of the textures
  15649. * @param format defines the format of the data
  15650. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15651. * @param generateMipMaps defines if the engine should generate the mip levels
  15652. * @param invertY defines if data must be stored with Y axis inverted
  15653. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15654. * @param compression defines the compression used (null by default)
  15655. * @returns the cube texture as an InternalTexture
  15656. */
  15657. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15658. if (compression === void 0) { compression = null; }
  15659. var gl = this._gl;
  15660. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15661. texture.isCube = true;
  15662. texture.generateMipMaps = generateMipMaps;
  15663. texture.format = format;
  15664. texture.type = type;
  15665. if (!this._doNotHandleContextLost) {
  15666. texture._bufferViewArray = data;
  15667. }
  15668. var textureType = this._getWebGLTextureType(type);
  15669. var internalFormat = this._getInternalFormat(format);
  15670. if (internalFormat === gl.RGB) {
  15671. internalFormat = gl.RGBA;
  15672. }
  15673. var width = size;
  15674. var height = width;
  15675. texture.width = width;
  15676. texture.height = height;
  15677. // Double check on POT to generate Mips.
  15678. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15679. if (!isPot) {
  15680. generateMipMaps = false;
  15681. }
  15682. // Upload data if needed. The texture won't be ready until then.
  15683. if (data) {
  15684. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15685. }
  15686. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15687. // Filters
  15688. if (data && generateMipMaps) {
  15689. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15690. }
  15691. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15694. }
  15695. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15698. }
  15699. else {
  15700. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15703. }
  15704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15706. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15707. return texture;
  15708. };
  15709. /**
  15710. * Creates a new raw cube texture from a specified url
  15711. * @param url defines the url where the data is located
  15712. * @param scene defines the current scene
  15713. * @param size defines the size of the textures
  15714. * @param format defines the format of the data
  15715. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15716. * @param noMipmap defines if the engine should avoid generating the mip levels
  15717. * @param callback defines a callback used to extract texture data from loaded data
  15718. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15719. * @param onLoad defines a callback called when texture is loaded
  15720. * @param onError defines a callback called if there is an error
  15721. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15722. * @param invertY defines if data must be stored with Y axis inverted
  15723. * @returns the cube texture as an InternalTexture
  15724. */
  15725. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15726. var _this = this;
  15727. if (onLoad === void 0) { onLoad = null; }
  15728. if (onError === void 0) { onError = null; }
  15729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15730. if (invertY === void 0) { invertY = false; }
  15731. var gl = this._gl;
  15732. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15733. scene._addPendingData(texture);
  15734. texture.url = url;
  15735. this._internalTexturesCache.push(texture);
  15736. var onerror = function (request, exception) {
  15737. scene._removePendingData(texture);
  15738. if (onError && request) {
  15739. onError(request.status + " " + request.statusText, exception);
  15740. }
  15741. };
  15742. var internalCallback = function (data) {
  15743. var width = texture.width;
  15744. var faceDataArrays = callback(data);
  15745. if (!faceDataArrays) {
  15746. return;
  15747. }
  15748. if (mipmapGenerator) {
  15749. var textureType = _this._getWebGLTextureType(type);
  15750. var internalFormat = _this._getInternalFormat(format);
  15751. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15752. var needConversion = false;
  15753. if (internalFormat === gl.RGB) {
  15754. internalFormat = gl.RGBA;
  15755. needConversion = true;
  15756. }
  15757. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15758. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15759. var mipData = mipmapGenerator(faceDataArrays);
  15760. for (var level = 0; level < mipData.length; level++) {
  15761. var mipSize = width >> level;
  15762. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15763. var mipFaceData = mipData[level][faceIndex];
  15764. if (needConversion) {
  15765. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15766. }
  15767. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15768. }
  15769. }
  15770. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15771. }
  15772. else {
  15773. texture.generateMipMaps = !noMipmap;
  15774. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15775. }
  15776. texture.isReady = true;
  15777. // this.resetTextureCache();
  15778. scene._removePendingData(texture);
  15779. if (onLoad) {
  15780. onLoad();
  15781. }
  15782. };
  15783. this._loadFile(url, function (data) {
  15784. internalCallback(data);
  15785. }, undefined, scene.database, true, onerror);
  15786. return texture;
  15787. };
  15788. ;
  15789. /**
  15790. * Update a raw 3D texture
  15791. * @param texture defines the texture to update
  15792. * @param data defines the data to store
  15793. * @param format defines the data format
  15794. * @param invertY defines if data must be stored with Y axis inverted
  15795. * @param compression defines the used compression (can be null)
  15796. */
  15797. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15798. if (compression === void 0) { compression = null; }
  15799. var internalFormat = this._getInternalFormat(format);
  15800. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15801. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15802. if (!this._doNotHandleContextLost) {
  15803. texture._bufferView = data;
  15804. texture.format = format;
  15805. texture.invertY = invertY;
  15806. texture._compression = compression;
  15807. }
  15808. if (texture.width % 4 !== 0) {
  15809. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15810. }
  15811. if (compression && data) {
  15812. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15813. }
  15814. else {
  15815. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15816. }
  15817. if (texture.generateMipMaps) {
  15818. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15819. }
  15820. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15821. // this.resetTextureCache();
  15822. texture.isReady = true;
  15823. };
  15824. /**
  15825. * Creates a new raw 3D texture
  15826. * @param data defines the data used to create the texture
  15827. * @param width defines the width of the texture
  15828. * @param height defines the height of the texture
  15829. * @param depth defines the depth of the texture
  15830. * @param format defines the format of the texture
  15831. * @param generateMipMaps defines if the engine must generate mip levels
  15832. * @param invertY defines if data must be stored with Y axis inverted
  15833. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15834. * @param compression defines the compressed used (can be null)
  15835. * @returns a new raw 3D texture (stored in an InternalTexture)
  15836. */
  15837. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15838. if (compression === void 0) { compression = null; }
  15839. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15840. texture.baseWidth = width;
  15841. texture.baseHeight = height;
  15842. texture.baseDepth = depth;
  15843. texture.width = width;
  15844. texture.height = height;
  15845. texture.depth = depth;
  15846. texture.format = format;
  15847. texture.generateMipMaps = generateMipMaps;
  15848. texture.samplingMode = samplingMode;
  15849. texture.is3D = true;
  15850. if (!this._doNotHandleContextLost) {
  15851. texture._bufferView = data;
  15852. }
  15853. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15854. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15855. // Filters
  15856. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15857. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15858. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15859. if (generateMipMaps) {
  15860. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15861. }
  15862. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15863. this._internalTexturesCache.push(texture);
  15864. return texture;
  15865. };
  15866. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15867. var gl = this._gl;
  15868. if (!gl) {
  15869. return;
  15870. }
  15871. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15874. if (!noMipmap && !isCompressed) {
  15875. gl.generateMipmap(gl.TEXTURE_2D);
  15876. }
  15877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15878. // this.resetTextureCache();
  15879. if (scene) {
  15880. scene._removePendingData(texture);
  15881. }
  15882. texture.onLoadedObservable.notifyObservers(texture);
  15883. texture.onLoadedObservable.clear();
  15884. };
  15885. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15886. var _this = this;
  15887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15888. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15889. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15890. var gl = this._gl;
  15891. if (!gl) {
  15892. return;
  15893. }
  15894. if (!texture._webGLTexture) {
  15895. // this.resetTextureCache();
  15896. if (scene) {
  15897. scene._removePendingData(texture);
  15898. }
  15899. return;
  15900. }
  15901. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15902. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15903. texture.baseWidth = width;
  15904. texture.baseHeight = height;
  15905. texture.width = potWidth;
  15906. texture.height = potHeight;
  15907. texture.isReady = true;
  15908. if (processFunction(potWidth, potHeight, function () {
  15909. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15910. })) {
  15911. // Returning as texture needs extra async steps
  15912. return;
  15913. }
  15914. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15915. };
  15916. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15917. // Create new RGBA data container.
  15918. var rgbaData;
  15919. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15920. rgbaData = new Float32Array(width * height * 4);
  15921. }
  15922. else {
  15923. rgbaData = new Uint32Array(width * height * 4);
  15924. }
  15925. // Convert each pixel.
  15926. for (var x = 0; x < width; x++) {
  15927. for (var y = 0; y < height; y++) {
  15928. var index = (y * width + x) * 3;
  15929. var newIndex = (y * width + x) * 4;
  15930. // Map Old Value to new value.
  15931. rgbaData[newIndex + 0] = rgbData[index + 0];
  15932. rgbaData[newIndex + 1] = rgbData[index + 1];
  15933. rgbaData[newIndex + 2] = rgbData[index + 2];
  15934. // Add fully opaque alpha channel.
  15935. rgbaData[newIndex + 3] = 1;
  15936. }
  15937. }
  15938. return rgbaData;
  15939. };
  15940. /** @ignore */
  15941. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15942. var gl = this._gl;
  15943. if (texture._framebuffer) {
  15944. gl.deleteFramebuffer(texture._framebuffer);
  15945. texture._framebuffer = null;
  15946. }
  15947. if (texture._depthStencilBuffer) {
  15948. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15949. texture._depthStencilBuffer = null;
  15950. }
  15951. if (texture._MSAAFramebuffer) {
  15952. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15953. texture._MSAAFramebuffer = null;
  15954. }
  15955. if (texture._MSAARenderBuffer) {
  15956. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15957. texture._MSAARenderBuffer = null;
  15958. }
  15959. };
  15960. /** @ignore */
  15961. Engine.prototype._releaseTexture = function (texture) {
  15962. var gl = this._gl;
  15963. this._releaseFramebufferObjects(texture);
  15964. gl.deleteTexture(texture._webGLTexture);
  15965. // Unbind channels
  15966. this.unbindAllTextures();
  15967. var index = this._internalTexturesCache.indexOf(texture);
  15968. if (index !== -1) {
  15969. this._internalTexturesCache.splice(index, 1);
  15970. }
  15971. // Integrated fixed lod samplers.
  15972. if (texture._lodTextureHigh) {
  15973. texture._lodTextureHigh.dispose();
  15974. }
  15975. if (texture._lodTextureMid) {
  15976. texture._lodTextureMid.dispose();
  15977. }
  15978. if (texture._lodTextureLow) {
  15979. texture._lodTextureLow.dispose();
  15980. }
  15981. // Set output texture of post process to null if the texture has been released/disposed
  15982. this.scenes.forEach(function (scene) {
  15983. scene.postProcesses.forEach(function (postProcess) {
  15984. if (postProcess._outputTexture == texture) {
  15985. postProcess._outputTexture = null;
  15986. }
  15987. });
  15988. scene.cameras.forEach(function (camera) {
  15989. camera._postProcesses.forEach(function (postProcess) {
  15990. if (postProcess) {
  15991. if (postProcess._outputTexture == texture) {
  15992. postProcess._outputTexture = null;
  15993. }
  15994. }
  15995. });
  15996. });
  15997. });
  15998. };
  15999. Engine.prototype.setProgram = function (program) {
  16000. if (this._currentProgram !== program) {
  16001. this._gl.useProgram(program);
  16002. this._currentProgram = program;
  16003. }
  16004. };
  16005. /**
  16006. * Binds an effect to the webGL context
  16007. * @param effect defines the effect to bind
  16008. */
  16009. Engine.prototype.bindSamplers = function (effect) {
  16010. this.setProgram(effect.getProgram());
  16011. var samplers = effect.getSamplers();
  16012. for (var index = 0; index < samplers.length; index++) {
  16013. var uniform = effect.getUniform(samplers[index]);
  16014. if (uniform) {
  16015. this._boundUniforms[index] = uniform;
  16016. }
  16017. }
  16018. this._currentEffect = null;
  16019. };
  16020. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16021. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16022. return;
  16023. }
  16024. // Remove
  16025. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16026. // Bind last to it
  16027. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16028. // Bind to dummy
  16029. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16030. };
  16031. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16032. if (!internalTexture) {
  16033. return -1;
  16034. }
  16035. internalTexture._initialSlot = channel;
  16036. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16037. if (channel !== internalTexture._designatedSlot) {
  16038. this._textureCollisions.addCount(1, false);
  16039. }
  16040. }
  16041. else {
  16042. if (channel !== internalTexture._designatedSlot) {
  16043. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16044. return internalTexture._designatedSlot;
  16045. }
  16046. else {
  16047. // No slot for this texture, let's pick a new one (if we find a free slot)
  16048. if (this._nextFreeTextureSlots.length) {
  16049. return this._nextFreeTextureSlots[0];
  16050. }
  16051. // We need to recycle the oldest bound texture, sorry.
  16052. this._textureCollisions.addCount(1, false);
  16053. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16054. }
  16055. }
  16056. }
  16057. return channel;
  16058. };
  16059. Engine.prototype._linkTrackers = function (previous, next) {
  16060. previous.next = next;
  16061. next.previous = previous;
  16062. };
  16063. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16064. var currentSlot = internalTexture._designatedSlot;
  16065. if (currentSlot === -1) {
  16066. return -1;
  16067. }
  16068. internalTexture._designatedSlot = -1;
  16069. if (this.disableTextureBindingOptimization) {
  16070. return -1;
  16071. }
  16072. // Remove from bound list
  16073. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16074. // Free the slot
  16075. this._boundTexturesCache[currentSlot] = null;
  16076. this._nextFreeTextureSlots.push(currentSlot);
  16077. return currentSlot;
  16078. };
  16079. Engine.prototype._activateCurrentTexture = function () {
  16080. if (this._currentTextureChannel !== this._activeChannel) {
  16081. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16082. this._currentTextureChannel = this._activeChannel;
  16083. }
  16084. };
  16085. /** @ignore */
  16086. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16087. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16088. if (force === void 0) { force = false; }
  16089. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16090. this._activeChannel = texture._designatedSlot;
  16091. }
  16092. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16093. var isTextureForRendering = texture && texture._initialSlot > -1;
  16094. if (currentTextureBound !== texture || force) {
  16095. if (currentTextureBound) {
  16096. this._removeDesignatedSlot(currentTextureBound);
  16097. }
  16098. this._activateCurrentTexture();
  16099. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16100. this._boundTexturesCache[this._activeChannel] = texture;
  16101. if (texture) {
  16102. if (!this.disableTextureBindingOptimization) {
  16103. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16104. if (slotIndex > -1) {
  16105. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16106. }
  16107. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16108. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16109. }
  16110. texture._designatedSlot = this._activeChannel;
  16111. }
  16112. }
  16113. else if (forTextureDataUpdate) {
  16114. this._activateCurrentTexture();
  16115. }
  16116. if (isTextureForRendering && !forTextureDataUpdate) {
  16117. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16118. }
  16119. };
  16120. /** @ignore */
  16121. Engine.prototype._bindTexture = function (channel, texture) {
  16122. if (channel < 0) {
  16123. return;
  16124. }
  16125. if (texture) {
  16126. channel = this._getCorrectTextureChannel(channel, texture);
  16127. }
  16128. this._activeChannel = channel;
  16129. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16130. };
  16131. /**
  16132. * Sets a texture to the webGL context from a postprocess
  16133. * @param channel defines the channel to use
  16134. * @param postProcess defines the source postprocess
  16135. */
  16136. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16137. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16138. };
  16139. /**
  16140. * Binds the output of the passed in post process to the texture channel specified
  16141. * @param channel The channel the texture should be bound to
  16142. * @param postProcess The post process which's output should be bound
  16143. */
  16144. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16145. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16146. };
  16147. /**
  16148. * Unbind all textures from the webGL context
  16149. */
  16150. Engine.prototype.unbindAllTextures = function () {
  16151. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16152. this._activeChannel = channel;
  16153. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16154. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16155. if (this.webGLVersion > 1) {
  16156. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16157. }
  16158. }
  16159. };
  16160. /**
  16161. * Sets a texture to the according uniform.
  16162. * @param channel The texture channel
  16163. * @param uniform The uniform to set
  16164. * @param texture The texture to apply
  16165. */
  16166. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16167. if (channel < 0) {
  16168. return;
  16169. }
  16170. if (uniform) {
  16171. this._boundUniforms[channel] = uniform;
  16172. }
  16173. this._setTexture(channel, texture);
  16174. };
  16175. /**
  16176. * Sets a depth stencil texture from a render target to the according uniform.
  16177. * @param channel The texture channel
  16178. * @param uniform The uniform to set
  16179. * @param texture The render target texture containing the depth stencil texture to apply
  16180. */
  16181. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16182. if (channel < 0) {
  16183. return;
  16184. }
  16185. if (uniform) {
  16186. this._boundUniforms[channel] = uniform;
  16187. }
  16188. if (!texture || !texture.depthStencilTexture) {
  16189. this._setTexture(channel, null);
  16190. }
  16191. else {
  16192. this._setTexture(channel, texture, false, true);
  16193. }
  16194. };
  16195. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16196. var uniform = this._boundUniforms[sourceSlot];
  16197. if (uniform._currentState === destination) {
  16198. return;
  16199. }
  16200. this._gl.uniform1i(uniform, destination);
  16201. uniform._currentState = destination;
  16202. };
  16203. Engine.prototype._getTextureWrapMode = function (mode) {
  16204. switch (mode) {
  16205. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16206. return this._gl.REPEAT;
  16207. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16208. return this._gl.CLAMP_TO_EDGE;
  16209. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16210. return this._gl.MIRRORED_REPEAT;
  16211. }
  16212. return this._gl.REPEAT;
  16213. };
  16214. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16215. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16216. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16217. // Not ready?
  16218. if (!texture) {
  16219. if (this._boundTexturesCache[channel] != null) {
  16220. this._activeChannel = channel;
  16221. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16222. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16223. if (this.webGLVersion > 1) {
  16224. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16225. }
  16226. }
  16227. return false;
  16228. }
  16229. // Video
  16230. if (texture.video) {
  16231. this._activeChannel = channel;
  16232. texture.update();
  16233. }
  16234. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16235. texture.delayLoad();
  16236. return false;
  16237. }
  16238. var internalTexture;
  16239. if (depthStencilTexture) {
  16240. internalTexture = texture.depthStencilTexture;
  16241. }
  16242. else if (texture.isReady()) {
  16243. internalTexture = texture.getInternalTexture();
  16244. }
  16245. else if (texture.isCube) {
  16246. internalTexture = this.emptyCubeTexture;
  16247. }
  16248. else if (texture.is3D) {
  16249. internalTexture = this.emptyTexture3D;
  16250. }
  16251. else {
  16252. internalTexture = this.emptyTexture;
  16253. }
  16254. if (!isPartOfTextureArray) {
  16255. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16256. }
  16257. var needToBind = true;
  16258. if (this._boundTexturesCache[channel] === internalTexture) {
  16259. this._moveBoundTextureOnTop(internalTexture);
  16260. if (!isPartOfTextureArray) {
  16261. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16262. }
  16263. needToBind = false;
  16264. }
  16265. this._activeChannel = channel;
  16266. if (internalTexture && internalTexture.is3D) {
  16267. if (needToBind) {
  16268. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16269. }
  16270. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16271. internalTexture._cachedWrapU = texture.wrapU;
  16272. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16273. }
  16274. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16275. internalTexture._cachedWrapV = texture.wrapV;
  16276. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16277. }
  16278. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16279. internalTexture._cachedWrapR = texture.wrapR;
  16280. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16281. }
  16282. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16283. }
  16284. else if (internalTexture && internalTexture.isCube) {
  16285. if (needToBind) {
  16286. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16287. }
  16288. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16289. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16290. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16291. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16292. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16293. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16294. }
  16295. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16296. }
  16297. else {
  16298. if (needToBind) {
  16299. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16300. }
  16301. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16302. internalTexture._cachedWrapU = texture.wrapU;
  16303. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16304. }
  16305. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16306. internalTexture._cachedWrapV = texture.wrapV;
  16307. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16308. }
  16309. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16310. }
  16311. return true;
  16312. };
  16313. /**
  16314. * Sets an array of texture to the webGL context
  16315. * @param channel defines the channel where the texture array must be set
  16316. * @param uniform defines the associated uniform location
  16317. * @param textures defines the array of textures to bind
  16318. */
  16319. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16320. if (channel < 0 || !uniform) {
  16321. return;
  16322. }
  16323. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16324. this._textureUnits = new Int32Array(textures.length);
  16325. }
  16326. for (var i = 0; i < textures.length; i++) {
  16327. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16328. }
  16329. this._gl.uniform1iv(uniform, this._textureUnits);
  16330. for (var index = 0; index < textures.length; index++) {
  16331. this._setTexture(this._textureUnits[index], textures[index], true);
  16332. }
  16333. };
  16334. /** @ignore */
  16335. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16336. var internalTexture = texture.getInternalTexture();
  16337. if (!internalTexture) {
  16338. return;
  16339. }
  16340. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16341. var value = texture.anisotropicFilteringLevel;
  16342. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16343. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16344. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16345. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16346. }
  16347. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16348. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16349. internalTexture._cachedAnisotropicFilteringLevel = value;
  16350. }
  16351. };
  16352. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16353. this._bindTextureDirectly(target, texture, true, true);
  16354. this._gl.texParameterf(target, parameter, value);
  16355. };
  16356. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16357. if (texture) {
  16358. this._bindTextureDirectly(target, texture, true, true);
  16359. }
  16360. this._gl.texParameteri(target, parameter, value);
  16361. };
  16362. /**
  16363. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16364. * @param x defines the x coordinate of the rectangle where pixels must be read
  16365. * @param y defines the y coordinate of the rectangle where pixels must be read
  16366. * @param width defines the width of the rectangle where pixels must be read
  16367. * @param height defines the height of the rectangle where pixels must be read
  16368. * @returns a Uint8Array containing RGBA colors
  16369. */
  16370. Engine.prototype.readPixels = function (x, y, width, height) {
  16371. var data = new Uint8Array(height * width * 4);
  16372. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16373. return data;
  16374. };
  16375. /**
  16376. * Add an externaly attached data from its key.
  16377. * This method call will fail and return false, if such key already exists.
  16378. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16379. * @param key the unique key that identifies the data
  16380. * @param data the data object to associate to the key for this Engine instance
  16381. * @return true if no such key were already present and the data was added successfully, false otherwise
  16382. */
  16383. Engine.prototype.addExternalData = function (key, data) {
  16384. if (!this._externalData) {
  16385. this._externalData = new BABYLON.StringDictionary();
  16386. }
  16387. return this._externalData.add(key, data);
  16388. };
  16389. /**
  16390. * Get an externaly attached data from its key
  16391. * @param key the unique key that identifies the data
  16392. * @return the associated data, if present (can be null), or undefined if not present
  16393. */
  16394. Engine.prototype.getExternalData = function (key) {
  16395. if (!this._externalData) {
  16396. this._externalData = new BABYLON.StringDictionary();
  16397. }
  16398. return this._externalData.get(key);
  16399. };
  16400. /**
  16401. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16402. * @param key the unique key that identifies the data
  16403. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16404. * @return the associated data, can be null if the factory returned null.
  16405. */
  16406. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16407. if (!this._externalData) {
  16408. this._externalData = new BABYLON.StringDictionary();
  16409. }
  16410. return this._externalData.getOrAddWithFactory(key, factory);
  16411. };
  16412. /**
  16413. * Remove an externaly attached data from the Engine instance
  16414. * @param key the unique key that identifies the data
  16415. * @return true if the data was successfully removed, false if it doesn't exist
  16416. */
  16417. Engine.prototype.removeExternalData = function (key) {
  16418. if (!this._externalData) {
  16419. this._externalData = new BABYLON.StringDictionary();
  16420. }
  16421. return this._externalData.remove(key);
  16422. };
  16423. /**
  16424. * Unbind all vertex attributes from the webGL context
  16425. */
  16426. Engine.prototype.unbindAllAttributes = function () {
  16427. if (this._mustWipeVertexAttributes) {
  16428. this._mustWipeVertexAttributes = false;
  16429. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16430. this._gl.disableVertexAttribArray(i);
  16431. this._vertexAttribArraysEnabled[i] = false;
  16432. this._currentBufferPointers[i].active = false;
  16433. }
  16434. return;
  16435. }
  16436. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16437. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16438. continue;
  16439. }
  16440. this._gl.disableVertexAttribArray(i);
  16441. this._vertexAttribArraysEnabled[i] = false;
  16442. this._currentBufferPointers[i].active = false;
  16443. }
  16444. };
  16445. /**
  16446. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16447. */
  16448. Engine.prototype.releaseEffects = function () {
  16449. for (var name in this._compiledEffects) {
  16450. this._deleteProgram(this._compiledEffects[name]._program);
  16451. }
  16452. this._compiledEffects = {};
  16453. };
  16454. /**
  16455. * Dispose and release all associated resources
  16456. */
  16457. Engine.prototype.dispose = function () {
  16458. this.hideLoadingUI();
  16459. this.stopRenderLoop();
  16460. // Release postProcesses
  16461. while (this.postProcesses.length) {
  16462. this.postProcesses[0].dispose();
  16463. }
  16464. // Empty texture
  16465. if (this._emptyTexture) {
  16466. this._releaseTexture(this._emptyTexture);
  16467. this._emptyTexture = null;
  16468. }
  16469. if (this._emptyCubeTexture) {
  16470. this._releaseTexture(this._emptyCubeTexture);
  16471. this._emptyCubeTexture = null;
  16472. }
  16473. // Rescale PP
  16474. if (this._rescalePostProcess) {
  16475. this._rescalePostProcess.dispose();
  16476. }
  16477. // Release scenes
  16478. while (this.scenes.length) {
  16479. this.scenes[0].dispose();
  16480. }
  16481. // Release audio engine
  16482. if (Engine.audioEngine) {
  16483. Engine.audioEngine.dispose();
  16484. }
  16485. // Release effects
  16486. this.releaseEffects();
  16487. // Unbind
  16488. this.unbindAllAttributes();
  16489. this._boundUniforms = [];
  16490. if (this._dummyFramebuffer) {
  16491. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16492. }
  16493. //WebVR
  16494. this.disableVR();
  16495. // Events
  16496. if (BABYLON.Tools.IsWindowObjectExist()) {
  16497. window.removeEventListener("blur", this._onBlur);
  16498. window.removeEventListener("focus", this._onFocus);
  16499. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16500. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16501. if (this._renderingCanvas) {
  16502. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16503. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16504. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16505. if (!this._doNotHandleContextLost) {
  16506. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16507. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16508. }
  16509. }
  16510. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16511. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16512. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16513. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16514. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16515. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16516. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16517. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16518. if (this._onVrDisplayConnect) {
  16519. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16520. if (this._onVrDisplayDisconnect) {
  16521. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16522. }
  16523. if (this._onVrDisplayPresentChange) {
  16524. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16525. }
  16526. this._onVrDisplayConnect = null;
  16527. this._onVrDisplayDisconnect = null;
  16528. }
  16529. }
  16530. // Remove from Instances
  16531. var index = Engine.Instances.indexOf(this);
  16532. if (index >= 0) {
  16533. Engine.Instances.splice(index, 1);
  16534. }
  16535. this._workingCanvas = null;
  16536. this._workingContext = null;
  16537. this._currentBufferPointers = [];
  16538. this._renderingCanvas = null;
  16539. this._currentProgram = null;
  16540. this._bindedRenderFunction = null;
  16541. this.onResizeObservable.clear();
  16542. this.onCanvasBlurObservable.clear();
  16543. this.onCanvasFocusObservable.clear();
  16544. this.onCanvasPointerOutObservable.clear();
  16545. this.onBeginFrameObservable.clear();
  16546. this.onEndFrameObservable.clear();
  16547. BABYLON.Effect.ResetCache();
  16548. // Abort active requests
  16549. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16550. var request = _a[_i];
  16551. request.abort();
  16552. }
  16553. };
  16554. // Loading screen
  16555. /**
  16556. * Display the loading screen
  16557. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16558. */
  16559. Engine.prototype.displayLoadingUI = function () {
  16560. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16561. return;
  16562. }
  16563. var loadingScreen = this.loadingScreen;
  16564. if (loadingScreen) {
  16565. loadingScreen.displayLoadingUI();
  16566. }
  16567. };
  16568. /**
  16569. * Hide the loading screen
  16570. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16571. */
  16572. Engine.prototype.hideLoadingUI = function () {
  16573. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16574. return;
  16575. }
  16576. var loadingScreen = this.loadingScreen;
  16577. if (loadingScreen) {
  16578. loadingScreen.hideLoadingUI();
  16579. }
  16580. };
  16581. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16582. /**
  16583. * Gets the current loading screen object
  16584. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16585. */
  16586. get: function () {
  16587. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16588. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16589. return this._loadingScreen;
  16590. },
  16591. /**
  16592. * Sets the current loading screen object
  16593. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16594. */
  16595. set: function (loadingScreen) {
  16596. this._loadingScreen = loadingScreen;
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16602. /**
  16603. * Sets the current loading screen text
  16604. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16605. */
  16606. set: function (text) {
  16607. this.loadingScreen.loadingUIText = text;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16613. /**
  16614. * Sets the current loading screen background color
  16615. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16616. */
  16617. set: function (color) {
  16618. this.loadingScreen.loadingUIBackgroundColor = color;
  16619. },
  16620. enumerable: true,
  16621. configurable: true
  16622. });
  16623. /**
  16624. * Attach a new callback raised when context lost event is fired
  16625. * @param callback defines the callback to call
  16626. */
  16627. Engine.prototype.attachContextLostEvent = function (callback) {
  16628. if (this._renderingCanvas) {
  16629. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16630. }
  16631. };
  16632. /**
  16633. * Attach a new callback raised when context restored event is fired
  16634. * @param callback defines the callback to call
  16635. */
  16636. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16637. if (this._renderingCanvas) {
  16638. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16639. }
  16640. };
  16641. /**
  16642. * Gets the source code of the vertex shader associated with a specific webGL program
  16643. * @param program defines the program to use
  16644. * @returns a string containing the source code of the vertex shader associated with the program
  16645. */
  16646. Engine.prototype.getVertexShaderSource = function (program) {
  16647. var shaders = this._gl.getAttachedShaders(program);
  16648. if (!shaders) {
  16649. return null;
  16650. }
  16651. return this._gl.getShaderSource(shaders[0]);
  16652. };
  16653. /**
  16654. * Gets the source code of the fragment shader associated with a specific webGL program
  16655. * @param program defines the program to use
  16656. * @returns a string containing the source code of the fragment shader associated with the program
  16657. */
  16658. Engine.prototype.getFragmentShaderSource = function (program) {
  16659. var shaders = this._gl.getAttachedShaders(program);
  16660. if (!shaders) {
  16661. return null;
  16662. }
  16663. return this._gl.getShaderSource(shaders[1]);
  16664. };
  16665. /**
  16666. * Get the current error code of the webGL context
  16667. * @returns the error code
  16668. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16669. */
  16670. Engine.prototype.getError = function () {
  16671. return this._gl.getError();
  16672. };
  16673. // FPS
  16674. /**
  16675. * Gets the current framerate
  16676. * @returns a number representing the framerate
  16677. */
  16678. Engine.prototype.getFps = function () {
  16679. return this._fps;
  16680. };
  16681. /**
  16682. * Gets the time spent between current and previous frame
  16683. * @returns a number representing the delta time in ms
  16684. */
  16685. Engine.prototype.getDeltaTime = function () {
  16686. return this._deltaTime;
  16687. };
  16688. Engine.prototype._measureFps = function () {
  16689. this._performanceMonitor.sampleFrame();
  16690. this._fps = this._performanceMonitor.averageFPS;
  16691. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16692. };
  16693. /** @ignore */
  16694. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16695. if (faceIndex === void 0) { faceIndex = -1; }
  16696. var gl = this._gl;
  16697. if (!this._dummyFramebuffer) {
  16698. var dummy = gl.createFramebuffer();
  16699. if (!dummy) {
  16700. throw new Error("Unable to create dummy framebuffer");
  16701. }
  16702. this._dummyFramebuffer = dummy;
  16703. }
  16704. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16705. if (faceIndex > -1) {
  16706. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16707. }
  16708. else {
  16709. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16710. }
  16711. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16712. var buffer;
  16713. switch (readType) {
  16714. case gl.UNSIGNED_BYTE:
  16715. buffer = new Uint8Array(4 * width * height);
  16716. readType = gl.UNSIGNED_BYTE;
  16717. break;
  16718. default:
  16719. buffer = new Float32Array(4 * width * height);
  16720. readType = gl.FLOAT;
  16721. break;
  16722. }
  16723. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16724. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16725. return buffer;
  16726. };
  16727. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16728. if (this._webGLVersion > 1) {
  16729. return this._caps.colorBufferFloat;
  16730. }
  16731. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16732. };
  16733. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16734. if (this._webGLVersion > 1) {
  16735. return this._caps.colorBufferFloat;
  16736. }
  16737. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16738. };
  16739. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16740. Engine.prototype._canRenderToFramebuffer = function (type) {
  16741. var gl = this._gl;
  16742. //clear existing errors
  16743. while (gl.getError() !== gl.NO_ERROR) { }
  16744. var successful = true;
  16745. var texture = gl.createTexture();
  16746. gl.bindTexture(gl.TEXTURE_2D, texture);
  16747. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16748. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16749. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16750. var fb = gl.createFramebuffer();
  16751. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16752. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16753. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16754. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16755. successful = successful && (gl.getError() === gl.NO_ERROR);
  16756. //try render by clearing frame buffer's color buffer
  16757. if (successful) {
  16758. gl.clear(gl.COLOR_BUFFER_BIT);
  16759. successful = successful && (gl.getError() === gl.NO_ERROR);
  16760. }
  16761. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16762. if (successful) {
  16763. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16764. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16765. var readFormat = gl.RGBA;
  16766. var readType = gl.UNSIGNED_BYTE;
  16767. var buffer = new Uint8Array(4);
  16768. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16769. successful = successful && (gl.getError() === gl.NO_ERROR);
  16770. }
  16771. //clean up
  16772. gl.deleteTexture(texture);
  16773. gl.deleteFramebuffer(fb);
  16774. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16775. //clear accumulated errors
  16776. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16777. return successful;
  16778. };
  16779. /** @ignore */
  16780. Engine.prototype._getWebGLTextureType = function (type) {
  16781. if (type === Engine.TEXTURETYPE_FLOAT) {
  16782. return this._gl.FLOAT;
  16783. }
  16784. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16785. // Add Half Float Constant.
  16786. return this._gl.HALF_FLOAT_OES;
  16787. }
  16788. return this._gl.UNSIGNED_BYTE;
  16789. };
  16790. ;
  16791. Engine.prototype._getInternalFormat = function (format) {
  16792. var internalFormat = this._gl.RGBA;
  16793. switch (format) {
  16794. case Engine.TEXTUREFORMAT_ALPHA:
  16795. internalFormat = this._gl.ALPHA;
  16796. break;
  16797. case Engine.TEXTUREFORMAT_LUMINANCE:
  16798. internalFormat = this._gl.LUMINANCE;
  16799. break;
  16800. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16801. internalFormat = this._gl.LUMINANCE_ALPHA;
  16802. break;
  16803. case Engine.TEXTUREFORMAT_RGB:
  16804. case Engine.TEXTUREFORMAT_RGB32F:
  16805. internalFormat = this._gl.RGB;
  16806. break;
  16807. case Engine.TEXTUREFORMAT_RGBA:
  16808. case Engine.TEXTUREFORMAT_RGBA32F:
  16809. internalFormat = this._gl.RGBA;
  16810. break;
  16811. case Engine.TEXTUREFORMAT_R32F:
  16812. internalFormat = this._gl.RED;
  16813. break;
  16814. case Engine.TEXTUREFORMAT_RG32F:
  16815. internalFormat = this._gl.RG;
  16816. break;
  16817. }
  16818. return internalFormat;
  16819. };
  16820. /** @ignore */
  16821. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16822. if (this._webGLVersion === 1) {
  16823. if (format) {
  16824. switch (format) {
  16825. case Engine.TEXTUREFORMAT_LUMINANCE:
  16826. return this._gl.LUMINANCE;
  16827. }
  16828. }
  16829. return this._gl.RGBA;
  16830. }
  16831. if (type === Engine.TEXTURETYPE_FLOAT) {
  16832. if (format) {
  16833. switch (format) {
  16834. case Engine.TEXTUREFORMAT_R32F:
  16835. return this._gl.R32F;
  16836. case Engine.TEXTUREFORMAT_RG32F:
  16837. return this._gl.RG32F;
  16838. case Engine.TEXTUREFORMAT_RGB32F:
  16839. return this._gl.RGB32F;
  16840. }
  16841. }
  16842. return this._gl.RGBA32F;
  16843. }
  16844. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16845. return this._gl.RGBA16F;
  16846. }
  16847. if (format) {
  16848. switch (format) {
  16849. case Engine.TEXTUREFORMAT_LUMINANCE:
  16850. return this._gl.LUMINANCE;
  16851. }
  16852. }
  16853. return this._gl.RGBA;
  16854. };
  16855. ;
  16856. /** @ignore */
  16857. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16858. if (type === Engine.TEXTURETYPE_FLOAT) {
  16859. return this._gl.RGBA32F;
  16860. }
  16861. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16862. return this._gl.RGBA16F;
  16863. }
  16864. return this._gl.RGBA8;
  16865. };
  16866. ;
  16867. /**
  16868. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16869. * @return the new query
  16870. */
  16871. Engine.prototype.createQuery = function () {
  16872. return this._gl.createQuery();
  16873. };
  16874. /**
  16875. * Delete and release a webGL query
  16876. * @param query defines the query to delete
  16877. * @return the current engine
  16878. */
  16879. Engine.prototype.deleteQuery = function (query) {
  16880. this._gl.deleteQuery(query);
  16881. return this;
  16882. };
  16883. /**
  16884. * Check if a given query has resolved and got its value
  16885. * @param query defines the query to check
  16886. * @returns true if the query got its value
  16887. */
  16888. Engine.prototype.isQueryResultAvailable = function (query) {
  16889. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16890. };
  16891. /**
  16892. * Gets the value of a given query
  16893. * @param query defines the query to check
  16894. * @returns the value of the query
  16895. */
  16896. Engine.prototype.getQueryResult = function (query) {
  16897. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16898. };
  16899. /**
  16900. * Initiates an occlusion query
  16901. * @param algorithmType defines the algorithm to use
  16902. * @param query defines the query to use
  16903. * @returns the current engine
  16904. * @see http://doc.babylonjs.com/features/occlusionquery
  16905. */
  16906. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16907. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16908. this._gl.beginQuery(glAlgorithm, query);
  16909. return this;
  16910. };
  16911. /**
  16912. * Ends an occlusion query
  16913. * @see http://doc.babylonjs.com/features/occlusionquery
  16914. * @param algorithmType defines the algorithm to use
  16915. * @returns the current engine
  16916. */
  16917. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16918. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16919. this._gl.endQuery(glAlgorithm);
  16920. return this;
  16921. };
  16922. /* Time queries */
  16923. Engine.prototype._createTimeQuery = function () {
  16924. var timerQuery = this._caps.timerQuery;
  16925. if (timerQuery.createQueryEXT) {
  16926. return timerQuery.createQueryEXT();
  16927. }
  16928. return this.createQuery();
  16929. };
  16930. Engine.prototype._deleteTimeQuery = function (query) {
  16931. var timerQuery = this._caps.timerQuery;
  16932. if (timerQuery.deleteQueryEXT) {
  16933. timerQuery.deleteQueryEXT(query);
  16934. return;
  16935. }
  16936. this.deleteQuery(query);
  16937. };
  16938. Engine.prototype._getTimeQueryResult = function (query) {
  16939. var timerQuery = this._caps.timerQuery;
  16940. if (timerQuery.getQueryObjectEXT) {
  16941. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16942. }
  16943. return this.getQueryResult(query);
  16944. };
  16945. Engine.prototype._getTimeQueryAvailability = function (query) {
  16946. var timerQuery = this._caps.timerQuery;
  16947. if (timerQuery.getQueryObjectEXT) {
  16948. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16949. }
  16950. return this.isQueryResultAvailable(query);
  16951. };
  16952. /**
  16953. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16954. * Please note that only one query can be issued at a time
  16955. * @returns a time token used to track the time span
  16956. */
  16957. Engine.prototype.startTimeQuery = function () {
  16958. var timerQuery = this._caps.timerQuery;
  16959. if (!timerQuery) {
  16960. return null;
  16961. }
  16962. var token = new BABYLON._TimeToken();
  16963. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16964. if (this._caps.canUseTimestampForTimerQuery) {
  16965. token._startTimeQuery = this._createTimeQuery();
  16966. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16967. }
  16968. else {
  16969. if (this._currentNonTimestampToken) {
  16970. return this._currentNonTimestampToken;
  16971. }
  16972. token._timeElapsedQuery = this._createTimeQuery();
  16973. if (timerQuery.beginQueryEXT) {
  16974. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16975. }
  16976. else {
  16977. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16978. }
  16979. this._currentNonTimestampToken = token;
  16980. }
  16981. return token;
  16982. };
  16983. /**
  16984. * Ends a time query
  16985. * @param token defines the token used to measure the time span
  16986. * @returns the time spent (in ns)
  16987. */
  16988. Engine.prototype.endTimeQuery = function (token) {
  16989. var timerQuery = this._caps.timerQuery;
  16990. if (!timerQuery || !token) {
  16991. return -1;
  16992. }
  16993. if (this._caps.canUseTimestampForTimerQuery) {
  16994. if (!token._startTimeQuery) {
  16995. return -1;
  16996. }
  16997. if (!token._endTimeQuery) {
  16998. token._endTimeQuery = this._createTimeQuery();
  16999. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17000. }
  17001. }
  17002. else if (!token._timeElapsedQueryEnded) {
  17003. if (!token._timeElapsedQuery) {
  17004. return -1;
  17005. }
  17006. if (timerQuery.endQueryEXT) {
  17007. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17008. }
  17009. else {
  17010. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17011. }
  17012. token._timeElapsedQueryEnded = true;
  17013. }
  17014. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17015. var available = false;
  17016. if (token._endTimeQuery) {
  17017. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17018. }
  17019. else if (token._timeElapsedQuery) {
  17020. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17021. }
  17022. if (available && !disjoint) {
  17023. var result = 0;
  17024. if (this._caps.canUseTimestampForTimerQuery) {
  17025. if (!token._startTimeQuery || !token._endTimeQuery) {
  17026. return -1;
  17027. }
  17028. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17029. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17030. result = timeEnd - timeStart;
  17031. this._deleteTimeQuery(token._startTimeQuery);
  17032. this._deleteTimeQuery(token._endTimeQuery);
  17033. token._startTimeQuery = null;
  17034. token._endTimeQuery = null;
  17035. }
  17036. else {
  17037. if (!token._timeElapsedQuery) {
  17038. return -1;
  17039. }
  17040. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17041. this._deleteTimeQuery(token._timeElapsedQuery);
  17042. token._timeElapsedQuery = null;
  17043. token._timeElapsedQueryEnded = false;
  17044. this._currentNonTimestampToken = null;
  17045. }
  17046. return result;
  17047. }
  17048. return -1;
  17049. };
  17050. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17051. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17052. };
  17053. // Transform feedback
  17054. /**
  17055. * Creates a webGL transform feedback object
  17056. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17057. * @returns the webGL transform feedback object
  17058. */
  17059. Engine.prototype.createTransformFeedback = function () {
  17060. return this._gl.createTransformFeedback();
  17061. };
  17062. /**
  17063. * Delete a webGL transform feedback object
  17064. * @param value defines the webGL transform feedback object to delete
  17065. */
  17066. Engine.prototype.deleteTransformFeedback = function (value) {
  17067. this._gl.deleteTransformFeedback(value);
  17068. };
  17069. /**
  17070. * Bind a webGL transform feedback object to the webgl context
  17071. * @param value defines the webGL transform feedback object to bind
  17072. */
  17073. Engine.prototype.bindTransformFeedback = function (value) {
  17074. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17075. };
  17076. /**
  17077. * Begins a transform feedback operation
  17078. * @param usePoints defines if points or triangles must be used
  17079. */
  17080. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17081. if (usePoints === void 0) { usePoints = true; }
  17082. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17083. };
  17084. /**
  17085. * Ends a transform feedback operation
  17086. */
  17087. Engine.prototype.endTransformFeedback = function () {
  17088. this._gl.endTransformFeedback();
  17089. };
  17090. /**
  17091. * Specify the varyings to use with transform feedback
  17092. * @param program defines the associated webGL program
  17093. * @param value defines the list of strings representing the varying names
  17094. */
  17095. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17096. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17097. };
  17098. /**
  17099. * Bind a webGL buffer for a transform feedback operation
  17100. * @param value defines the webGL buffer to bind
  17101. */
  17102. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17103. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17104. };
  17105. /** @ignore */
  17106. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17107. var _this = this;
  17108. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17109. this._activeRequests.push(request);
  17110. request.onCompleteObservable.add(function (request) {
  17111. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17112. });
  17113. return request;
  17114. };
  17115. /** @ignore */
  17116. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17117. var _this = this;
  17118. return new Promise(function (resolve, reject) {
  17119. _this._loadFile(url, function (data) {
  17120. resolve(data);
  17121. }, undefined, database, useArrayBuffer, function (request, exception) {
  17122. reject(exception);
  17123. });
  17124. });
  17125. };
  17126. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17127. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17128. var onload = function (data) {
  17129. loadedFiles[index] = data;
  17130. loadedFiles._internalCount++;
  17131. if (loadedFiles._internalCount === 6) {
  17132. onfinish(loadedFiles);
  17133. }
  17134. };
  17135. var onerror = function (request, exception) {
  17136. if (onErrorCallBack && request) {
  17137. onErrorCallBack(request.status + " " + request.statusText, exception);
  17138. }
  17139. };
  17140. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17141. };
  17142. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17143. if (onError === void 0) { onError = null; }
  17144. var loadedFiles = [];
  17145. loadedFiles._internalCount = 0;
  17146. for (var index = 0; index < 6; index++) {
  17147. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17148. }
  17149. };
  17150. // Statics
  17151. /**
  17152. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17153. * @returns true if the engine can be created
  17154. * @ignoreNaming
  17155. */
  17156. Engine.isSupported = function () {
  17157. try {
  17158. var tempcanvas = document.createElement("canvas");
  17159. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17160. return gl != null && !!window.WebGLRenderingContext;
  17161. }
  17162. catch (e) {
  17163. return false;
  17164. }
  17165. };
  17166. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17167. Engine.ExceptionList = [
  17168. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17169. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17170. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17171. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17172. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17173. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17174. ];
  17175. /** Gets the list of created engines */
  17176. Engine.Instances = new Array();
  17177. // Const statics
  17178. Engine._ALPHA_DISABLE = 0;
  17179. Engine._ALPHA_ADD = 1;
  17180. Engine._ALPHA_COMBINE = 2;
  17181. Engine._ALPHA_SUBTRACT = 3;
  17182. Engine._ALPHA_MULTIPLY = 4;
  17183. Engine._ALPHA_MAXIMIZED = 5;
  17184. Engine._ALPHA_ONEONE = 6;
  17185. Engine._ALPHA_PREMULTIPLIED = 7;
  17186. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17187. Engine._ALPHA_INTERPOLATE = 9;
  17188. Engine._ALPHA_SCREENMODE = 10;
  17189. Engine._DELAYLOADSTATE_NONE = 0;
  17190. Engine._DELAYLOADSTATE_LOADED = 1;
  17191. Engine._DELAYLOADSTATE_LOADING = 2;
  17192. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17193. Engine._TEXTUREFORMAT_ALPHA = 0;
  17194. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17195. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17196. Engine._TEXTUREFORMAT_RGB = 4;
  17197. Engine._TEXTUREFORMAT_RGBA = 5;
  17198. Engine._TEXTUREFORMAT_R32F = 6;
  17199. Engine._TEXTUREFORMAT_RG32F = 7;
  17200. Engine._TEXTUREFORMAT_RGB32F = 8;
  17201. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17202. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17203. Engine._TEXTURETYPE_FLOAT = 1;
  17204. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17205. // Depht or Stencil test Constants.
  17206. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17207. 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.
  17208. 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.
  17209. 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.
  17210. 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.
  17211. 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.
  17212. 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.
  17213. 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.
  17214. // Stencil Actions Constants.
  17215. Engine._KEEP = 0x1E00;
  17216. Engine._REPLACE = 0x1E01;
  17217. Engine._INCR = 0x1E02;
  17218. Engine._DECR = 0x1E03;
  17219. Engine._INVERT = 0x150A;
  17220. Engine._INCR_WRAP = 0x8507;
  17221. Engine._DECR_WRAP = 0x8508;
  17222. // Texture rescaling mode
  17223. Engine._SCALEMODE_FLOOR = 1;
  17224. Engine._SCALEMODE_NEAREST = 2;
  17225. Engine._SCALEMODE_CEILING = 3;
  17226. // Updatable statics so stick with vars here
  17227. /**
  17228. * Gets or sets the epsilon value used by collision engine
  17229. */
  17230. Engine.CollisionsEpsilon = 0.001;
  17231. /**
  17232. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17233. */
  17234. Engine.CodeRepository = "src/";
  17235. /**
  17236. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17237. */
  17238. Engine.ShadersRepository = "src/Shaders/";
  17239. return Engine;
  17240. }());
  17241. BABYLON.Engine = Engine;
  17242. })(BABYLON || (BABYLON = {}));
  17243. //# sourceMappingURL=babylon.engine.js.map
  17244. var BABYLON;
  17245. (function (BABYLON) {
  17246. /**
  17247. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17248. */
  17249. var Node = /** @class */ (function () {
  17250. /**
  17251. * Creates a new Node
  17252. * @param {string} name - the name and id to be given to this node
  17253. * @param {BABYLON.Scene} the scene this node will be added to
  17254. */
  17255. function Node(name, scene) {
  17256. if (scene === void 0) { scene = null; }
  17257. /**
  17258. * Gets or sets a string used to store user defined state for the node
  17259. */
  17260. this.state = "";
  17261. /**
  17262. * Gets or sets an object used to store user defined information for the node
  17263. */
  17264. this.metadata = null;
  17265. /**
  17266. * Gets or sets a boolean used to define if the node must be serialized
  17267. */
  17268. this.doNotSerialize = false;
  17269. /** @ignore */
  17270. this._isDisposed = false;
  17271. /**
  17272. * Gets a list of Animations associated with the node
  17273. */
  17274. this.animations = new Array();
  17275. this._ranges = {};
  17276. this._isEnabled = true;
  17277. this._isReady = true;
  17278. /** @ignore */
  17279. this._currentRenderId = -1;
  17280. this._parentRenderId = -1;
  17281. this._childRenderId = -1;
  17282. this._animationPropertiesOverride = null;
  17283. /**
  17284. * An event triggered when the mesh is disposed
  17285. */
  17286. this.onDisposeObservable = new BABYLON.Observable();
  17287. // Behaviors
  17288. this._behaviors = new Array();
  17289. this.name = name;
  17290. this.id = name;
  17291. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17292. this.uniqueId = this._scene.getUniqueId();
  17293. this._initCache();
  17294. }
  17295. /**
  17296. * Gets a boolean indicating if the node has been disposed
  17297. * @returns true if the node was disposed
  17298. */
  17299. Node.prototype.isDisposed = function () {
  17300. return this._isDisposed;
  17301. };
  17302. Object.defineProperty(Node.prototype, "parent", {
  17303. get: function () {
  17304. return this._parentNode;
  17305. },
  17306. /**
  17307. * Gets or sets the parent of the node
  17308. */
  17309. set: function (parent) {
  17310. if (this._parentNode === parent) {
  17311. return;
  17312. }
  17313. // Remove self from list of children of parent
  17314. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17315. var index = this._parentNode._children.indexOf(this);
  17316. if (index !== -1) {
  17317. this._parentNode._children.splice(index, 1);
  17318. }
  17319. }
  17320. // Store new parent
  17321. this._parentNode = parent;
  17322. // Add as child to new parent
  17323. if (this._parentNode) {
  17324. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17325. this._parentNode._children = new Array();
  17326. }
  17327. this._parentNode._children.push(this);
  17328. }
  17329. },
  17330. enumerable: true,
  17331. configurable: true
  17332. });
  17333. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17334. /**
  17335. * Gets or sets the animation properties override
  17336. */
  17337. get: function () {
  17338. if (!this._animationPropertiesOverride) {
  17339. return this._scene.animationPropertiesOverride;
  17340. }
  17341. return this._animationPropertiesOverride;
  17342. },
  17343. set: function (value) {
  17344. this._animationPropertiesOverride = value;
  17345. },
  17346. enumerable: true,
  17347. configurable: true
  17348. });
  17349. /**
  17350. * Gets a string idenfifying the name of the class
  17351. * @returns "Node" string
  17352. */
  17353. Node.prototype.getClassName = function () {
  17354. return "Node";
  17355. };
  17356. Object.defineProperty(Node.prototype, "onDispose", {
  17357. /**
  17358. * Sets a callback that will be raised when the node will be disposed
  17359. */
  17360. set: function (callback) {
  17361. if (this._onDisposeObserver) {
  17362. this.onDisposeObservable.remove(this._onDisposeObserver);
  17363. }
  17364. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17365. },
  17366. enumerable: true,
  17367. configurable: true
  17368. });
  17369. /**
  17370. * Gets the scene of the node
  17371. * @returns a {BABYLON.Scene}
  17372. */
  17373. Node.prototype.getScene = function () {
  17374. return this._scene;
  17375. };
  17376. /**
  17377. * Gets the engine of the node
  17378. * @returns a {BABYLON.Engine}
  17379. */
  17380. Node.prototype.getEngine = function () {
  17381. return this._scene.getEngine();
  17382. };
  17383. /**
  17384. * Attach a behavior to the node
  17385. * @see http://doc.babylonjs.com/features/behaviour
  17386. * @param behavior defines the behavior to attach
  17387. * @returns the current Node
  17388. */
  17389. Node.prototype.addBehavior = function (behavior) {
  17390. var _this = this;
  17391. var index = this._behaviors.indexOf(behavior);
  17392. if (index !== -1) {
  17393. return this;
  17394. }
  17395. behavior.init();
  17396. if (this._scene.isLoading) {
  17397. // We defer the attach when the scene will be loaded
  17398. var observer = this._scene.onDataLoadedObservable.add(function () {
  17399. behavior.attach(_this);
  17400. setTimeout(function () {
  17401. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17402. _this._scene.onDataLoadedObservable.remove(observer);
  17403. }, 0);
  17404. });
  17405. }
  17406. else {
  17407. behavior.attach(this);
  17408. }
  17409. this._behaviors.push(behavior);
  17410. return this;
  17411. };
  17412. /**
  17413. * Remove an attached behavior
  17414. * @see http://doc.babylonjs.com/features/behaviour
  17415. * @param behavior defines the behavior to attach
  17416. * @returns the current Node
  17417. */
  17418. Node.prototype.removeBehavior = function (behavior) {
  17419. var index = this._behaviors.indexOf(behavior);
  17420. if (index === -1) {
  17421. return this;
  17422. }
  17423. this._behaviors[index].detach();
  17424. this._behaviors.splice(index, 1);
  17425. return this;
  17426. };
  17427. Object.defineProperty(Node.prototype, "behaviors", {
  17428. /**
  17429. * Gets the list of attached behaviors
  17430. * @see http://doc.babylonjs.com/features/behaviour
  17431. */
  17432. get: function () {
  17433. return this._behaviors;
  17434. },
  17435. enumerable: true,
  17436. configurable: true
  17437. });
  17438. /**
  17439. * Gets an attached behavior by name
  17440. * @param name defines the name of the behavior to look for
  17441. * @see http://doc.babylonjs.com/features/behaviour
  17442. * @returns null if behavior was not found else the requested behavior
  17443. */
  17444. Node.prototype.getBehaviorByName = function (name) {
  17445. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17446. var behavior = _a[_i];
  17447. if (behavior.name === name) {
  17448. return behavior;
  17449. }
  17450. }
  17451. return null;
  17452. };
  17453. /**
  17454. * Returns the world matrix of the node
  17455. * @returns a matrix containing the node's world matrix
  17456. */
  17457. Node.prototype.getWorldMatrix = function () {
  17458. return BABYLON.Matrix.Identity();
  17459. };
  17460. // override it in derived class if you add new variables to the cache
  17461. // and call the parent class method
  17462. /** @ignore */
  17463. Node.prototype._initCache = function () {
  17464. this._cache = {};
  17465. this._cache.parent = undefined;
  17466. };
  17467. /** @ignore */
  17468. Node.prototype.updateCache = function (force) {
  17469. if (!force && this.isSynchronized())
  17470. return;
  17471. this._cache.parent = this.parent;
  17472. this._updateCache();
  17473. };
  17474. // override it in derived class if you add new variables to the cache
  17475. // and call the parent class method if !ignoreParentClass
  17476. /** @ignore */
  17477. Node.prototype._updateCache = function (ignoreParentClass) {
  17478. };
  17479. // override it in derived class if you add new variables to the cache
  17480. /** @ignore */
  17481. Node.prototype._isSynchronized = function () {
  17482. return true;
  17483. };
  17484. /** @ignore */
  17485. Node.prototype._markSyncedWithParent = function () {
  17486. if (this.parent) {
  17487. this._parentRenderId = this.parent._childRenderId;
  17488. }
  17489. };
  17490. /** @ignore */
  17491. Node.prototype.isSynchronizedWithParent = function () {
  17492. if (!this.parent) {
  17493. return true;
  17494. }
  17495. if (this._parentRenderId !== this.parent._childRenderId) {
  17496. return false;
  17497. }
  17498. return this.parent.isSynchronized();
  17499. };
  17500. /** @ignore */
  17501. Node.prototype.isSynchronized = function (updateCache) {
  17502. var check = this.hasNewParent();
  17503. check = check || !this.isSynchronizedWithParent();
  17504. check = check || !this._isSynchronized();
  17505. if (updateCache)
  17506. this.updateCache(true);
  17507. return !check;
  17508. };
  17509. /** @ignore */
  17510. Node.prototype.hasNewParent = function (update) {
  17511. if (this._cache.parent === this.parent)
  17512. return false;
  17513. if (update)
  17514. this._cache.parent = this.parent;
  17515. return true;
  17516. };
  17517. /**
  17518. * Is this node ready to be used/rendered
  17519. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17520. * @return true if the node is ready
  17521. */
  17522. Node.prototype.isReady = function (completeCheck) {
  17523. if (completeCheck === void 0) { completeCheck = false; }
  17524. return this._isReady;
  17525. };
  17526. /**
  17527. * Is this node enabled?
  17528. * 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
  17529. * @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
  17530. * @return whether this node (and its parent) is enabled
  17531. */
  17532. Node.prototype.isEnabled = function (checkAncestors) {
  17533. if (checkAncestors === void 0) { checkAncestors = true; }
  17534. if (checkAncestors === false) {
  17535. return this._isEnabled;
  17536. }
  17537. if (this._isEnabled === false) {
  17538. return false;
  17539. }
  17540. if (this.parent !== undefined && this.parent !== null) {
  17541. return this.parent.isEnabled(checkAncestors);
  17542. }
  17543. return true;
  17544. };
  17545. /**
  17546. * Set the enabled state of this node
  17547. * @param value defines the new enabled state
  17548. */
  17549. Node.prototype.setEnabled = function (value) {
  17550. this._isEnabled = value;
  17551. };
  17552. /**
  17553. * Is this node a descendant of the given node?
  17554. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17555. * @param ancestor defines the parent node to inspect
  17556. * @returns a boolean indicating if this node is a descendant of the given node
  17557. */
  17558. Node.prototype.isDescendantOf = function (ancestor) {
  17559. if (this.parent) {
  17560. if (this.parent === ancestor) {
  17561. return true;
  17562. }
  17563. return this.parent.isDescendantOf(ancestor);
  17564. }
  17565. return false;
  17566. };
  17567. /** @ignore */
  17568. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17569. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17570. if (!this._children) {
  17571. return;
  17572. }
  17573. for (var index = 0; index < this._children.length; index++) {
  17574. var item = this._children[index];
  17575. if (!predicate || predicate(item)) {
  17576. results.push(item);
  17577. }
  17578. if (!directDescendantsOnly) {
  17579. item._getDescendants(results, false, predicate);
  17580. }
  17581. }
  17582. };
  17583. /**
  17584. * Will return all nodes that have this node as ascendant
  17585. * @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
  17586. * @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
  17587. * @return all children nodes of all types
  17588. */
  17589. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17590. var results = new Array();
  17591. this._getDescendants(results, directDescendantsOnly, predicate);
  17592. return results;
  17593. };
  17594. /**
  17595. * Get all child-meshes of this node
  17596. * @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
  17597. * @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
  17598. * @returns an array of {BABYLON.AbstractMesh}
  17599. */
  17600. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17601. var results = [];
  17602. this._getDescendants(results, directDescendantsOnly, function (node) {
  17603. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17604. });
  17605. return results;
  17606. };
  17607. /**
  17608. * Get all child-transformNodes of this node
  17609. * @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
  17610. * @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
  17611. * @returns an array of {BABYLON.TransformNode}
  17612. */
  17613. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17614. var results = [];
  17615. this._getDescendants(results, directDescendantsOnly, function (node) {
  17616. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17617. });
  17618. return results;
  17619. };
  17620. /**
  17621. * Get all direct children of this node
  17622. * @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
  17623. * @returns an array of {BABYLON.Node}
  17624. */
  17625. Node.prototype.getChildren = function (predicate) {
  17626. return this.getDescendants(true, predicate);
  17627. };
  17628. /** @ignore */
  17629. Node.prototype._setReady = function (state) {
  17630. if (state === this._isReady) {
  17631. return;
  17632. }
  17633. if (!state) {
  17634. this._isReady = false;
  17635. return;
  17636. }
  17637. if (this.onReady) {
  17638. this.onReady(this);
  17639. }
  17640. this._isReady = true;
  17641. };
  17642. /**
  17643. * Get an animation by name
  17644. * @param name defines the name of the animation to look for
  17645. * @returns null if not found else the requested animation
  17646. */
  17647. Node.prototype.getAnimationByName = function (name) {
  17648. for (var i = 0; i < this.animations.length; i++) {
  17649. var animation = this.animations[i];
  17650. if (animation.name === name) {
  17651. return animation;
  17652. }
  17653. }
  17654. return null;
  17655. };
  17656. /**
  17657. * Creates an animation range for this node
  17658. * @param name defines the name of the range
  17659. * @param from defines the starting key
  17660. * @param to defines the end key
  17661. */
  17662. Node.prototype.createAnimationRange = function (name, from, to) {
  17663. // check name not already in use
  17664. if (!this._ranges[name]) {
  17665. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17666. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17667. if (this.animations[i]) {
  17668. this.animations[i].createRange(name, from, to);
  17669. }
  17670. }
  17671. }
  17672. };
  17673. /**
  17674. * Delete a specific animation range
  17675. * @param name defines the name of the range to delete
  17676. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17677. */
  17678. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17679. if (deleteFrames === void 0) { deleteFrames = true; }
  17680. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17681. if (this.animations[i]) {
  17682. this.animations[i].deleteRange(name, deleteFrames);
  17683. }
  17684. }
  17685. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17686. };
  17687. /**
  17688. * Get an animation range by name
  17689. * @param name defines the name of the animation range to look for
  17690. * @returns null if not found else the requested animation range
  17691. */
  17692. Node.prototype.getAnimationRange = function (name) {
  17693. return this._ranges[name];
  17694. };
  17695. /**
  17696. * Will start the animation sequence
  17697. * @param name defines the range frames for animation sequence
  17698. * @param loop defines if the animation should loop (false by default)
  17699. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17700. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17701. * @returns the object created for this animation. If range does not exist, it will return null
  17702. */
  17703. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17704. var range = this.getAnimationRange(name);
  17705. if (!range) {
  17706. return null;
  17707. }
  17708. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17709. };
  17710. /**
  17711. * Serialize animation ranges into a JSON compatible object
  17712. * @returns serialization object
  17713. */
  17714. Node.prototype.serializeAnimationRanges = function () {
  17715. var serializationRanges = [];
  17716. for (var name in this._ranges) {
  17717. var localRange = this._ranges[name];
  17718. if (!localRange) {
  17719. continue;
  17720. }
  17721. var range = {};
  17722. range.name = name;
  17723. range.from = localRange.from;
  17724. range.to = localRange.to;
  17725. serializationRanges.push(range);
  17726. }
  17727. return serializationRanges;
  17728. };
  17729. /**
  17730. * Computes the world matrix of the node
  17731. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17732. * @returns the world matrix
  17733. */
  17734. Node.prototype.computeWorldMatrix = function (force) {
  17735. return BABYLON.Matrix.Identity();
  17736. };
  17737. /**
  17738. * Releases resources associated with this node.
  17739. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17740. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17741. */
  17742. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17743. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17744. if (!doNotRecurse) {
  17745. var nodes = this.getDescendants(true);
  17746. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17747. var node = nodes_1[_i];
  17748. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17749. }
  17750. }
  17751. else {
  17752. var transformNodes = this.getChildTransformNodes(true);
  17753. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17754. var transformNode = transformNodes_1[_a];
  17755. transformNode.parent = null;
  17756. transformNode.computeWorldMatrix(true);
  17757. }
  17758. }
  17759. this.parent = null;
  17760. // Callback
  17761. this.onDisposeObservable.notifyObservers(this);
  17762. this.onDisposeObservable.clear();
  17763. // Behaviors
  17764. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17765. var behavior = _c[_b];
  17766. behavior.detach();
  17767. }
  17768. this._behaviors = [];
  17769. this._isDisposed = true;
  17770. };
  17771. /**
  17772. * Parse animation range data from a serialization object and store them into a given node
  17773. * @param node defines where to store the animation ranges
  17774. * @param parsedNode defines the serialization object to read data from
  17775. * @param scene defines the hosting scene
  17776. */
  17777. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17778. if (parsedNode.ranges) {
  17779. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17780. var data = parsedNode.ranges[index];
  17781. node.createAnimationRange(data.name, data.from, data.to);
  17782. }
  17783. }
  17784. };
  17785. __decorate([
  17786. BABYLON.serialize()
  17787. ], Node.prototype, "name", void 0);
  17788. __decorate([
  17789. BABYLON.serialize()
  17790. ], Node.prototype, "id", void 0);
  17791. __decorate([
  17792. BABYLON.serialize()
  17793. ], Node.prototype, "uniqueId", void 0);
  17794. __decorate([
  17795. BABYLON.serialize()
  17796. ], Node.prototype, "state", void 0);
  17797. __decorate([
  17798. BABYLON.serialize()
  17799. ], Node.prototype, "metadata", void 0);
  17800. return Node;
  17801. }());
  17802. BABYLON.Node = Node;
  17803. })(BABYLON || (BABYLON = {}));
  17804. //# sourceMappingURL=babylon.node.js.map
  17805. var BABYLON;
  17806. (function (BABYLON) {
  17807. var BoundingSphere = /** @class */ (function () {
  17808. function BoundingSphere(minimum, maximum) {
  17809. this.minimum = minimum;
  17810. this.maximum = maximum;
  17811. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17812. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17813. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17814. this.radius = distance * 0.5;
  17815. this.centerWorld = BABYLON.Vector3.Zero();
  17816. this._update(BABYLON.Matrix.Identity());
  17817. }
  17818. // Methods
  17819. BoundingSphere.prototype._update = function (world) {
  17820. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17821. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17822. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17823. };
  17824. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17825. for (var i = 0; i < 6; i++) {
  17826. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17827. return false;
  17828. }
  17829. return true;
  17830. };
  17831. BoundingSphere.prototype.intersectsPoint = function (point) {
  17832. var x = this.centerWorld.x - point.x;
  17833. var y = this.centerWorld.y - point.y;
  17834. var z = this.centerWorld.z - point.z;
  17835. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17836. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17837. return false;
  17838. return true;
  17839. };
  17840. // Statics
  17841. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17842. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17843. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17844. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17845. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17846. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17847. return false;
  17848. return true;
  17849. };
  17850. return BoundingSphere;
  17851. }());
  17852. BABYLON.BoundingSphere = BoundingSphere;
  17853. })(BABYLON || (BABYLON = {}));
  17854. //# sourceMappingURL=babylon.boundingSphere.js.map
  17855. var BABYLON;
  17856. (function (BABYLON) {
  17857. var BoundingBox = /** @class */ (function () {
  17858. function BoundingBox(minimum, maximum) {
  17859. this.minimum = minimum;
  17860. this.maximum = maximum;
  17861. this.vectors = new Array();
  17862. this.vectorsWorld = new Array();
  17863. // Bounding vectors
  17864. this.vectors.push(this.minimum.clone());
  17865. this.vectors.push(this.maximum.clone());
  17866. this.vectors.push(this.minimum.clone());
  17867. this.vectors[2].x = this.maximum.x;
  17868. this.vectors.push(this.minimum.clone());
  17869. this.vectors[3].y = this.maximum.y;
  17870. this.vectors.push(this.minimum.clone());
  17871. this.vectors[4].z = this.maximum.z;
  17872. this.vectors.push(this.maximum.clone());
  17873. this.vectors[5].z = this.minimum.z;
  17874. this.vectors.push(this.maximum.clone());
  17875. this.vectors[6].x = this.minimum.x;
  17876. this.vectors.push(this.maximum.clone());
  17877. this.vectors[7].y = this.minimum.y;
  17878. // OBB
  17879. this.center = this.maximum.add(this.minimum).scale(0.5);
  17880. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17881. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17882. // World
  17883. for (var index = 0; index < this.vectors.length; index++) {
  17884. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17885. }
  17886. this.minimumWorld = BABYLON.Vector3.Zero();
  17887. this.maximumWorld = BABYLON.Vector3.Zero();
  17888. this.centerWorld = BABYLON.Vector3.Zero();
  17889. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17890. this._update(BABYLON.Matrix.Identity());
  17891. }
  17892. // Methods
  17893. BoundingBox.prototype.getWorldMatrix = function () {
  17894. return this._worldMatrix;
  17895. };
  17896. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17897. this._worldMatrix.copyFrom(matrix);
  17898. return this;
  17899. };
  17900. BoundingBox.prototype._update = function (world) {
  17901. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17902. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17903. for (var index = 0; index < this.vectors.length; index++) {
  17904. var v = this.vectorsWorld[index];
  17905. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17906. if (v.x < this.minimumWorld.x)
  17907. this.minimumWorld.x = v.x;
  17908. if (v.y < this.minimumWorld.y)
  17909. this.minimumWorld.y = v.y;
  17910. if (v.z < this.minimumWorld.z)
  17911. this.minimumWorld.z = v.z;
  17912. if (v.x > this.maximumWorld.x)
  17913. this.maximumWorld.x = v.x;
  17914. if (v.y > this.maximumWorld.y)
  17915. this.maximumWorld.y = v.y;
  17916. if (v.z > this.maximumWorld.z)
  17917. this.maximumWorld.z = v.z;
  17918. }
  17919. // Extend
  17920. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17921. this.extendSizeWorld.scaleInPlace(0.5);
  17922. // OBB
  17923. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17924. this.centerWorld.scaleInPlace(0.5);
  17925. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17926. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17927. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17928. this._worldMatrix = world;
  17929. };
  17930. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17931. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17932. };
  17933. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17934. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17935. };
  17936. BoundingBox.prototype.intersectsPoint = function (point) {
  17937. var delta = -BABYLON.Epsilon;
  17938. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17939. return false;
  17940. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17941. return false;
  17942. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17943. return false;
  17944. return true;
  17945. };
  17946. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17947. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17948. };
  17949. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17950. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17951. return false;
  17952. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17953. return false;
  17954. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17955. return false;
  17956. return true;
  17957. };
  17958. // Statics
  17959. BoundingBox.Intersects = function (box0, box1) {
  17960. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17961. return false;
  17962. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17963. return false;
  17964. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17965. return false;
  17966. return true;
  17967. };
  17968. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17969. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17970. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17971. return (num <= (sphereRadius * sphereRadius));
  17972. };
  17973. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17974. for (var p = 0; p < 6; p++) {
  17975. for (var i = 0; i < 8; i++) {
  17976. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17977. return false;
  17978. }
  17979. }
  17980. }
  17981. return true;
  17982. };
  17983. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17984. for (var p = 0; p < 6; p++) {
  17985. var inCount = 8;
  17986. for (var i = 0; i < 8; i++) {
  17987. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17988. --inCount;
  17989. }
  17990. else {
  17991. break;
  17992. }
  17993. }
  17994. if (inCount === 0)
  17995. return false;
  17996. }
  17997. return true;
  17998. };
  17999. return BoundingBox;
  18000. }());
  18001. BABYLON.BoundingBox = BoundingBox;
  18002. })(BABYLON || (BABYLON = {}));
  18003. //# sourceMappingURL=babylon.boundingBox.js.map
  18004. var BABYLON;
  18005. (function (BABYLON) {
  18006. var computeBoxExtents = function (axis, box) {
  18007. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18008. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18009. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18010. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18011. var r = r0 + r1 + r2;
  18012. return {
  18013. min: p - r,
  18014. max: p + r
  18015. };
  18016. };
  18017. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18018. var axisOverlap = function (axis, box0, box1) {
  18019. var result0 = computeBoxExtents(axis, box0);
  18020. var result1 = computeBoxExtents(axis, box1);
  18021. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18022. };
  18023. var BoundingInfo = /** @class */ (function () {
  18024. function BoundingInfo(minimum, maximum) {
  18025. this.minimum = minimum;
  18026. this.maximum = maximum;
  18027. this._isLocked = false;
  18028. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18029. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18030. }
  18031. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18032. get: function () {
  18033. return this._isLocked;
  18034. },
  18035. set: function (value) {
  18036. this._isLocked = value;
  18037. },
  18038. enumerable: true,
  18039. configurable: true
  18040. });
  18041. // Methods
  18042. BoundingInfo.prototype.update = function (world) {
  18043. if (this._isLocked) {
  18044. return;
  18045. }
  18046. this.boundingBox._update(world);
  18047. this.boundingSphere._update(world);
  18048. };
  18049. /**
  18050. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18051. * @param center New center of the bounding info
  18052. * @param extend New extend of the bounding info
  18053. */
  18054. BoundingInfo.prototype.centerOn = function (center, extend) {
  18055. this.minimum = center.subtract(extend);
  18056. this.maximum = center.add(extend);
  18057. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18058. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18059. return this;
  18060. };
  18061. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18062. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18063. return false;
  18064. return this.boundingBox.isInFrustum(frustumPlanes);
  18065. };
  18066. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18067. /**
  18068. * Gets the world distance between the min and max points of the bounding box
  18069. */
  18070. get: function () {
  18071. var boundingBox = this.boundingBox;
  18072. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18073. return size.length();
  18074. },
  18075. enumerable: true,
  18076. configurable: true
  18077. });
  18078. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18079. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18080. };
  18081. BoundingInfo.prototype._checkCollision = function (collider) {
  18082. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18083. };
  18084. BoundingInfo.prototype.intersectsPoint = function (point) {
  18085. if (!this.boundingSphere.centerWorld) {
  18086. return false;
  18087. }
  18088. if (!this.boundingSphere.intersectsPoint(point)) {
  18089. return false;
  18090. }
  18091. if (!this.boundingBox.intersectsPoint(point)) {
  18092. return false;
  18093. }
  18094. return true;
  18095. };
  18096. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18097. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18098. return false;
  18099. }
  18100. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18101. return false;
  18102. }
  18103. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18104. return false;
  18105. }
  18106. if (!precise) {
  18107. return true;
  18108. }
  18109. var box0 = this.boundingBox;
  18110. var box1 = boundingInfo.boundingBox;
  18111. if (!axisOverlap(box0.directions[0], box0, box1))
  18112. return false;
  18113. if (!axisOverlap(box0.directions[1], box0, box1))
  18114. return false;
  18115. if (!axisOverlap(box0.directions[2], box0, box1))
  18116. return false;
  18117. if (!axisOverlap(box1.directions[0], box0, box1))
  18118. return false;
  18119. if (!axisOverlap(box1.directions[1], box0, box1))
  18120. return false;
  18121. if (!axisOverlap(box1.directions[2], box0, box1))
  18122. return false;
  18123. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18124. return false;
  18125. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18126. return false;
  18127. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18128. return false;
  18129. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18130. return false;
  18131. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18132. return false;
  18133. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18134. return false;
  18135. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18136. return false;
  18137. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18138. return false;
  18139. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18140. return false;
  18141. return true;
  18142. };
  18143. return BoundingInfo;
  18144. }());
  18145. BABYLON.BoundingInfo = BoundingInfo;
  18146. })(BABYLON || (BABYLON = {}));
  18147. //# sourceMappingURL=babylon.boundingInfo.js.map
  18148. var BABYLON;
  18149. (function (BABYLON) {
  18150. var TransformNode = /** @class */ (function (_super) {
  18151. __extends(TransformNode, _super);
  18152. function TransformNode(name, scene, isPure) {
  18153. if (scene === void 0) { scene = null; }
  18154. if (isPure === void 0) { isPure = true; }
  18155. var _this = _super.call(this, name, scene) || this;
  18156. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18157. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18158. _this._up = new BABYLON.Vector3(0, 1, 0);
  18159. _this._right = new BABYLON.Vector3(1, 0, 0);
  18160. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18161. // Properties
  18162. _this._rotation = BABYLON.Vector3.Zero();
  18163. _this._scaling = BABYLON.Vector3.One();
  18164. _this._isDirty = false;
  18165. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18166. _this.scalingDeterminant = 1;
  18167. _this.infiniteDistance = false;
  18168. _this.position = BABYLON.Vector3.Zero();
  18169. _this._localWorld = BABYLON.Matrix.Zero();
  18170. _this._worldMatrix = BABYLON.Matrix.Zero();
  18171. _this._worldMatrixDeterminant = 0;
  18172. _this._absolutePosition = BABYLON.Vector3.Zero();
  18173. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18174. _this._postMultiplyPivotMatrix = false;
  18175. _this._isWorldMatrixFrozen = false;
  18176. /**
  18177. * An event triggered after the world matrix is updated
  18178. */
  18179. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18180. _this._nonUniformScaling = false;
  18181. if (isPure) {
  18182. _this.getScene().addTransformNode(_this);
  18183. }
  18184. return _this;
  18185. }
  18186. /**
  18187. * Gets a string idenfifying the name of the class
  18188. * @returns "TransformNode" string
  18189. */
  18190. TransformNode.prototype.getClassName = function () {
  18191. return "TransformNode";
  18192. };
  18193. Object.defineProperty(TransformNode.prototype, "rotation", {
  18194. /**
  18195. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18196. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18197. * Default : (0.0, 0.0, 0.0)
  18198. */
  18199. get: function () {
  18200. return this._rotation;
  18201. },
  18202. set: function (newRotation) {
  18203. this._rotation = newRotation;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. Object.defineProperty(TransformNode.prototype, "scaling", {
  18209. /**
  18210. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18211. * Default : (1.0, 1.0, 1.0)
  18212. */
  18213. get: function () {
  18214. return this._scaling;
  18215. },
  18216. /**
  18217. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18218. * Default : (1.0, 1.0, 1.0)
  18219. */
  18220. set: function (newScaling) {
  18221. this._scaling = newScaling;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18227. /**
  18228. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18229. * It's null by default.
  18230. * 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)
  18231. */
  18232. get: function () {
  18233. return this._rotationQuaternion;
  18234. },
  18235. set: function (quaternion) {
  18236. this._rotationQuaternion = quaternion;
  18237. //reset the rotation vector.
  18238. if (quaternion && this.rotation.length()) {
  18239. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18240. }
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. Object.defineProperty(TransformNode.prototype, "forward", {
  18246. /**
  18247. * The forward direction of that transform in world space.
  18248. */
  18249. get: function () {
  18250. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18251. },
  18252. enumerable: true,
  18253. configurable: true
  18254. });
  18255. Object.defineProperty(TransformNode.prototype, "up", {
  18256. /**
  18257. * The up direction of that transform in world space.
  18258. */
  18259. get: function () {
  18260. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18261. },
  18262. enumerable: true,
  18263. configurable: true
  18264. });
  18265. Object.defineProperty(TransformNode.prototype, "right", {
  18266. /**
  18267. * The right direction of that transform in world space.
  18268. */
  18269. get: function () {
  18270. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18271. },
  18272. enumerable: true,
  18273. configurable: true
  18274. });
  18275. /**
  18276. * Returns the latest update of the World matrix
  18277. * Returns a Matrix.
  18278. */
  18279. TransformNode.prototype.getWorldMatrix = function () {
  18280. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18281. this.computeWorldMatrix();
  18282. }
  18283. return this._worldMatrix;
  18284. };
  18285. /**
  18286. * Returns the latest update of the World matrix determinant.
  18287. */
  18288. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18289. return this._worldMatrixDeterminant;
  18290. };
  18291. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18292. /**
  18293. * Returns directly the latest state of the mesh World matrix.
  18294. * A Matrix is returned.
  18295. */
  18296. get: function () {
  18297. return this._worldMatrix;
  18298. },
  18299. enumerable: true,
  18300. configurable: true
  18301. });
  18302. /**
  18303. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18304. * Returns the TransformNode.
  18305. */
  18306. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18307. this._poseMatrix.copyFrom(matrix);
  18308. return this;
  18309. };
  18310. /**
  18311. * Returns the mesh Pose matrix.
  18312. * Returned object : Matrix
  18313. */
  18314. TransformNode.prototype.getPoseMatrix = function () {
  18315. return this._poseMatrix;
  18316. };
  18317. TransformNode.prototype._isSynchronized = function () {
  18318. if (this._isDirty) {
  18319. return false;
  18320. }
  18321. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18322. return false;
  18323. if (this._cache.pivotMatrixUpdated) {
  18324. return false;
  18325. }
  18326. if (this.infiniteDistance) {
  18327. return false;
  18328. }
  18329. if (!this._cache.position.equals(this.position))
  18330. return false;
  18331. if (this.rotationQuaternion) {
  18332. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18333. return false;
  18334. }
  18335. if (!this._cache.rotation.equals(this.rotation))
  18336. return false;
  18337. if (!this._cache.scaling.equals(this.scaling))
  18338. return false;
  18339. return true;
  18340. };
  18341. TransformNode.prototype._initCache = function () {
  18342. _super.prototype._initCache.call(this);
  18343. this._cache.localMatrixUpdated = false;
  18344. this._cache.position = BABYLON.Vector3.Zero();
  18345. this._cache.scaling = BABYLON.Vector3.Zero();
  18346. this._cache.rotation = BABYLON.Vector3.Zero();
  18347. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18348. this._cache.billboardMode = -1;
  18349. };
  18350. TransformNode.prototype.markAsDirty = function (property) {
  18351. if (property === "rotation") {
  18352. this.rotationQuaternion = null;
  18353. }
  18354. this._currentRenderId = Number.MAX_VALUE;
  18355. this._isDirty = true;
  18356. return this;
  18357. };
  18358. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18359. /**
  18360. * Returns the current mesh absolute position.
  18361. * Retuns a Vector3.
  18362. */
  18363. get: function () {
  18364. return this._absolutePosition;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. /**
  18370. * Sets a new matrix to apply before all other transformation
  18371. * @param matrix defines the transform matrix
  18372. * @returns the current TransformNode
  18373. */
  18374. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18375. return this.setPivotMatrix(matrix, false);
  18376. };
  18377. /**
  18378. * Sets a new pivot matrix to the current node
  18379. * @param matrix defines the new pivot matrix to use
  18380. * @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
  18381. * @returns the current TransformNode
  18382. */
  18383. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18384. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18385. this._pivotMatrix = matrix.clone();
  18386. this._cache.pivotMatrixUpdated = true;
  18387. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18388. if (this._postMultiplyPivotMatrix) {
  18389. if (!this._pivotMatrixInverse) {
  18390. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18391. }
  18392. else {
  18393. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18394. }
  18395. }
  18396. return this;
  18397. };
  18398. /**
  18399. * Returns the mesh pivot matrix.
  18400. * Default : Identity.
  18401. * A Matrix is returned.
  18402. */
  18403. TransformNode.prototype.getPivotMatrix = function () {
  18404. return this._pivotMatrix;
  18405. };
  18406. /**
  18407. * Prevents the World matrix to be computed any longer.
  18408. * Returns the TransformNode.
  18409. */
  18410. TransformNode.prototype.freezeWorldMatrix = function () {
  18411. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18412. this.computeWorldMatrix(true);
  18413. this._isWorldMatrixFrozen = true;
  18414. return this;
  18415. };
  18416. /**
  18417. * Allows back the World matrix computation.
  18418. * Returns the TransformNode.
  18419. */
  18420. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18421. this._isWorldMatrixFrozen = false;
  18422. this.computeWorldMatrix(true);
  18423. return this;
  18424. };
  18425. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18426. /**
  18427. * True if the World matrix has been frozen.
  18428. * Returns a boolean.
  18429. */
  18430. get: function () {
  18431. return this._isWorldMatrixFrozen;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. /**
  18437. * Retuns the mesh absolute position in the World.
  18438. * Returns a Vector3.
  18439. */
  18440. TransformNode.prototype.getAbsolutePosition = function () {
  18441. this.computeWorldMatrix();
  18442. return this._absolutePosition;
  18443. };
  18444. /**
  18445. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18446. * Returns the TransformNode.
  18447. */
  18448. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18449. if (!absolutePosition) {
  18450. return this;
  18451. }
  18452. var absolutePositionX;
  18453. var absolutePositionY;
  18454. var absolutePositionZ;
  18455. if (absolutePosition.x === undefined) {
  18456. if (arguments.length < 3) {
  18457. return this;
  18458. }
  18459. absolutePositionX = arguments[0];
  18460. absolutePositionY = arguments[1];
  18461. absolutePositionZ = arguments[2];
  18462. }
  18463. else {
  18464. absolutePositionX = absolutePosition.x;
  18465. absolutePositionY = absolutePosition.y;
  18466. absolutePositionZ = absolutePosition.z;
  18467. }
  18468. if (this.parent) {
  18469. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18470. invertParentWorldMatrix.invert();
  18471. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18472. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18473. }
  18474. else {
  18475. this.position.x = absolutePositionX;
  18476. this.position.y = absolutePositionY;
  18477. this.position.z = absolutePositionZ;
  18478. }
  18479. return this;
  18480. };
  18481. /**
  18482. * Sets the mesh position in its local space.
  18483. * Returns the TransformNode.
  18484. */
  18485. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18486. this.computeWorldMatrix();
  18487. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18488. return this;
  18489. };
  18490. /**
  18491. * Returns the mesh position in the local space from the current World matrix values.
  18492. * Returns a new Vector3.
  18493. */
  18494. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18495. this.computeWorldMatrix();
  18496. var invLocalWorldMatrix = this._localWorld.clone();
  18497. invLocalWorldMatrix.invert();
  18498. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18499. };
  18500. /**
  18501. * Translates the mesh along the passed Vector3 in its local space.
  18502. * Returns the TransformNode.
  18503. */
  18504. TransformNode.prototype.locallyTranslate = function (vector3) {
  18505. this.computeWorldMatrix(true);
  18506. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18507. return this;
  18508. };
  18509. /**
  18510. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18511. * @param targetPoint the position (must be in same space as current mesh) to look at
  18512. * @param yawCor optional yaw (y-axis) correction in radians
  18513. * @param pitchCor optional pitch (x-axis) correction in radians
  18514. * @param rollCor optional roll (z-axis) correction in radians
  18515. * @param space the choosen space of the target
  18516. * @returns the TransformNode.
  18517. */
  18518. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18519. if (yawCor === void 0) { yawCor = 0; }
  18520. if (pitchCor === void 0) { pitchCor = 0; }
  18521. if (rollCor === void 0) { rollCor = 0; }
  18522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18523. var dv = TransformNode._lookAtVectorCache;
  18524. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18525. targetPoint.subtractToRef(pos, dv);
  18526. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18527. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18528. var pitch = Math.atan2(dv.y, len);
  18529. if (this.rotationQuaternion) {
  18530. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18531. }
  18532. else {
  18533. this.rotation.x = pitch + pitchCor;
  18534. this.rotation.y = yaw + yawCor;
  18535. this.rotation.z = rollCor;
  18536. }
  18537. return this;
  18538. };
  18539. /**
  18540. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18541. * This Vector3 is expressed in the World space.
  18542. */
  18543. TransformNode.prototype.getDirection = function (localAxis) {
  18544. var result = BABYLON.Vector3.Zero();
  18545. this.getDirectionToRef(localAxis, result);
  18546. return result;
  18547. };
  18548. /**
  18549. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18550. * localAxis is expressed in the mesh local space.
  18551. * result is computed in the Wordl space from the mesh World matrix.
  18552. * Returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18555. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18556. return this;
  18557. };
  18558. /**
  18559. * Sets a new pivot point to the current node
  18560. * @param point defines the new pivot point to use
  18561. * @param space defines if the point is in world or local space (local by default)
  18562. * @returns the current TransformNode
  18563. */
  18564. TransformNode.prototype.setPivotPoint = function (point, space) {
  18565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18566. if (this.getScene().getRenderId() == 0) {
  18567. this.computeWorldMatrix(true);
  18568. }
  18569. var wm = this.getWorldMatrix();
  18570. if (space == BABYLON.Space.WORLD) {
  18571. var tmat = BABYLON.Tmp.Matrix[0];
  18572. wm.invertToRef(tmat);
  18573. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18574. }
  18575. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18576. };
  18577. /**
  18578. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18579. */
  18580. TransformNode.prototype.getPivotPoint = function () {
  18581. var point = BABYLON.Vector3.Zero();
  18582. this.getPivotPointToRef(point);
  18583. return point;
  18584. };
  18585. /**
  18586. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18587. * Returns the TransformNode.
  18588. */
  18589. TransformNode.prototype.getPivotPointToRef = function (result) {
  18590. result.x = -this._pivotMatrix.m[12];
  18591. result.y = -this._pivotMatrix.m[13];
  18592. result.z = -this._pivotMatrix.m[14];
  18593. return this;
  18594. };
  18595. /**
  18596. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18597. */
  18598. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18599. var point = BABYLON.Vector3.Zero();
  18600. this.getAbsolutePivotPointToRef(point);
  18601. return point;
  18602. };
  18603. /**
  18604. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18605. * Returns the TransformNode.
  18606. */
  18607. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18608. result.x = this._pivotMatrix.m[12];
  18609. result.y = this._pivotMatrix.m[13];
  18610. result.z = this._pivotMatrix.m[14];
  18611. this.getPivotPointToRef(result);
  18612. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18613. return this;
  18614. };
  18615. /**
  18616. * Defines the passed node as the parent of the current node.
  18617. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18618. * Returns the TransformNode.
  18619. */
  18620. TransformNode.prototype.setParent = function (node) {
  18621. if (node === null) {
  18622. var rotation = BABYLON.Tmp.Quaternion[0];
  18623. var position = BABYLON.Tmp.Vector3[0];
  18624. var scale = BABYLON.Tmp.Vector3[1];
  18625. if (this.parent && this.parent.computeWorldMatrix) {
  18626. this.parent.computeWorldMatrix(true);
  18627. }
  18628. this.computeWorldMatrix(true);
  18629. this.getWorldMatrix().decompose(scale, rotation, position);
  18630. if (this.rotationQuaternion) {
  18631. this.rotationQuaternion.copyFrom(rotation);
  18632. }
  18633. else {
  18634. rotation.toEulerAnglesToRef(this.rotation);
  18635. }
  18636. this.scaling.x = scale.x;
  18637. this.scaling.y = scale.y;
  18638. this.scaling.z = scale.z;
  18639. this.position.x = position.x;
  18640. this.position.y = position.y;
  18641. this.position.z = position.z;
  18642. }
  18643. else {
  18644. var rotation = BABYLON.Tmp.Quaternion[0];
  18645. var position = BABYLON.Tmp.Vector3[0];
  18646. var scale = BABYLON.Tmp.Vector3[1];
  18647. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18648. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18649. this.computeWorldMatrix(true);
  18650. node.computeWorldMatrix(true);
  18651. node.getWorldMatrix().invertToRef(invParentMatrix);
  18652. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18653. diffMatrix.decompose(scale, rotation, position);
  18654. if (this.rotationQuaternion) {
  18655. this.rotationQuaternion.copyFrom(rotation);
  18656. }
  18657. else {
  18658. rotation.toEulerAnglesToRef(this.rotation);
  18659. }
  18660. this.position.x = position.x;
  18661. this.position.y = position.y;
  18662. this.position.z = position.z;
  18663. this.scaling.x = scale.x;
  18664. this.scaling.y = scale.y;
  18665. this.scaling.z = scale.z;
  18666. }
  18667. this.parent = node;
  18668. return this;
  18669. };
  18670. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18671. get: function () {
  18672. return this._nonUniformScaling;
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18678. if (this._nonUniformScaling === value) {
  18679. return false;
  18680. }
  18681. this._nonUniformScaling = true;
  18682. return true;
  18683. };
  18684. /**
  18685. * Attach the current TransformNode to another TransformNode associated with a bone
  18686. * @param bone Bone affecting the TransformNode
  18687. * @param affectedTransformNode TransformNode associated with the bone
  18688. */
  18689. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18690. this._transformToBoneReferal = affectedTransformNode;
  18691. this.parent = bone;
  18692. if (bone.getWorldMatrix().determinant() < 0) {
  18693. this.scalingDeterminant *= -1;
  18694. }
  18695. return this;
  18696. };
  18697. TransformNode.prototype.detachFromBone = function () {
  18698. if (!this.parent) {
  18699. return this;
  18700. }
  18701. if (this.parent.getWorldMatrix().determinant() < 0) {
  18702. this.scalingDeterminant *= -1;
  18703. }
  18704. this._transformToBoneReferal = null;
  18705. this.parent = null;
  18706. return this;
  18707. };
  18708. /**
  18709. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18710. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18711. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18712. * The passed axis is also normalized.
  18713. * Returns the TransformNode.
  18714. */
  18715. TransformNode.prototype.rotate = function (axis, amount, space) {
  18716. axis.normalize();
  18717. if (!this.rotationQuaternion) {
  18718. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18719. this.rotation = BABYLON.Vector3.Zero();
  18720. }
  18721. var rotationQuaternion;
  18722. if (!space || space === BABYLON.Space.LOCAL) {
  18723. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18724. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18725. }
  18726. else {
  18727. if (this.parent) {
  18728. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18729. invertParentWorldMatrix.invert();
  18730. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18731. }
  18732. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18733. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18734. }
  18735. return this;
  18736. };
  18737. /**
  18738. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18739. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18740. * The passed axis is also normalized.
  18741. * Returns the TransformNode.
  18742. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18743. */
  18744. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18745. axis.normalize();
  18746. if (!this.rotationQuaternion) {
  18747. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18748. this.rotation.copyFromFloats(0, 0, 0);
  18749. }
  18750. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18751. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18752. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18753. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18754. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18755. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18756. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18757. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18758. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18759. return this;
  18760. };
  18761. /**
  18762. * Translates the mesh along the axis vector for the passed distance in the given space.
  18763. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18764. * Returns the TransformNode.
  18765. */
  18766. TransformNode.prototype.translate = function (axis, distance, space) {
  18767. var displacementVector = axis.scale(distance);
  18768. if (!space || space === BABYLON.Space.LOCAL) {
  18769. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18770. this.setPositionWithLocalVector(tempV3);
  18771. }
  18772. else {
  18773. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18774. }
  18775. return this;
  18776. };
  18777. /**
  18778. * Adds a rotation step to the mesh current rotation.
  18779. * x, y, z are Euler angles expressed in radians.
  18780. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18781. * This means this rotation is made in the mesh local space only.
  18782. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18783. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18784. * ```javascript
  18785. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18786. * ```
  18787. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18788. * 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.
  18789. * Returns the TransformNode.
  18790. */
  18791. TransformNode.prototype.addRotation = function (x, y, z) {
  18792. var rotationQuaternion;
  18793. if (this.rotationQuaternion) {
  18794. rotationQuaternion = this.rotationQuaternion;
  18795. }
  18796. else {
  18797. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18798. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18799. }
  18800. var accumulation = BABYLON.Tmp.Quaternion[0];
  18801. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18802. rotationQuaternion.multiplyInPlace(accumulation);
  18803. if (!this.rotationQuaternion) {
  18804. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18805. }
  18806. return this;
  18807. };
  18808. /**
  18809. * Computes the mesh World matrix and returns it.
  18810. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18811. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18812. * If the parameter `force`is set to `true`, the actual computation is done.
  18813. * Returns the mesh World Matrix.
  18814. */
  18815. TransformNode.prototype.computeWorldMatrix = function (force) {
  18816. if (this._isWorldMatrixFrozen) {
  18817. return this._worldMatrix;
  18818. }
  18819. if (!force && this.isSynchronized(true)) {
  18820. this._currentRenderId = this.getScene().getRenderId();
  18821. return this._worldMatrix;
  18822. }
  18823. this._cache.position.copyFrom(this.position);
  18824. this._cache.scaling.copyFrom(this.scaling);
  18825. this._cache.pivotMatrixUpdated = false;
  18826. this._cache.billboardMode = this.billboardMode;
  18827. this._currentRenderId = this.getScene().getRenderId();
  18828. this._childRenderId = this.getScene().getRenderId();
  18829. this._isDirty = false;
  18830. // Scaling
  18831. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18832. // Rotation
  18833. //rotate, if quaternion is set and rotation was used
  18834. if (this.rotationQuaternion) {
  18835. var len = this.rotation.length();
  18836. if (len) {
  18837. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18838. this.rotation.copyFromFloats(0, 0, 0);
  18839. }
  18840. }
  18841. if (this.rotationQuaternion) {
  18842. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18843. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18844. }
  18845. else {
  18846. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18847. this._cache.rotation.copyFrom(this.rotation);
  18848. }
  18849. // Translation
  18850. var camera = this.getScene().activeCamera;
  18851. if (this.infiniteDistance && !this.parent && camera) {
  18852. var cameraWorldMatrix = camera.getWorldMatrix();
  18853. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18854. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18855. }
  18856. else {
  18857. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18858. }
  18859. // Composing transformations
  18860. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18861. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18862. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18863. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18864. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18865. // Need to decompose each rotation here
  18866. var currentPosition = BABYLON.Tmp.Vector3[3];
  18867. if (this.parent && this.parent.getWorldMatrix) {
  18868. if (this._transformToBoneReferal) {
  18869. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18870. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18871. }
  18872. else {
  18873. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18874. }
  18875. }
  18876. else {
  18877. currentPosition.copyFrom(this.position);
  18878. }
  18879. currentPosition.subtractInPlace(camera.globalPosition);
  18880. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18881. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18882. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18883. }
  18884. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18885. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18886. }
  18887. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18888. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18889. }
  18890. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18891. }
  18892. else {
  18893. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18894. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18895. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18896. }
  18897. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18898. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18899. }
  18900. // Local world
  18901. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18902. // Parent
  18903. if (this.parent && this.parent.getWorldMatrix) {
  18904. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18905. if (this._transformToBoneReferal) {
  18906. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18907. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18908. }
  18909. else {
  18910. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18911. }
  18912. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18913. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18914. this._worldMatrix.copyFrom(this._localWorld);
  18915. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18916. }
  18917. else {
  18918. if (this._transformToBoneReferal) {
  18919. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18920. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18921. }
  18922. else {
  18923. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18924. }
  18925. }
  18926. this._markSyncedWithParent();
  18927. }
  18928. else {
  18929. this._worldMatrix.copyFrom(this._localWorld);
  18930. }
  18931. // Post multiply inverse of pivotMatrix
  18932. if (this._postMultiplyPivotMatrix) {
  18933. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18934. }
  18935. // Normal matrix
  18936. if (this.scaling.isNonUniform) {
  18937. this._updateNonUniformScalingState(true);
  18938. }
  18939. else if (this.parent && this.parent._nonUniformScaling) {
  18940. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18941. }
  18942. else {
  18943. this._updateNonUniformScalingState(false);
  18944. }
  18945. this._afterComputeWorldMatrix();
  18946. // Absolute position
  18947. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18948. // Callbacks
  18949. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18950. if (!this._poseMatrix) {
  18951. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18952. }
  18953. // Cache the determinant
  18954. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18955. return this._worldMatrix;
  18956. };
  18957. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18958. };
  18959. /**
  18960. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18961. * @param func: callback function to add
  18962. *
  18963. * Returns the TransformNode.
  18964. */
  18965. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18966. this.onAfterWorldMatrixUpdateObservable.add(func);
  18967. return this;
  18968. };
  18969. /**
  18970. * Removes a registered callback function.
  18971. * Returns the TransformNode.
  18972. */
  18973. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18974. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18975. return this;
  18976. };
  18977. /**
  18978. * Clone the current transform node
  18979. * Returns the new transform node
  18980. * @param name Name of the new clone
  18981. * @param newParent New parent for the clone
  18982. * @param doNotCloneChildren Do not clone children hierarchy
  18983. */
  18984. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18985. var _this = this;
  18986. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18987. result.name = name;
  18988. result.id = name;
  18989. if (newParent) {
  18990. result.parent = newParent;
  18991. }
  18992. if (!doNotCloneChildren) {
  18993. // Children
  18994. var directDescendants = this.getDescendants(true);
  18995. for (var index = 0; index < directDescendants.length; index++) {
  18996. var child = directDescendants[index];
  18997. if (child.clone) {
  18998. child.clone(name + "." + child.name, result);
  18999. }
  19000. }
  19001. }
  19002. return result;
  19003. };
  19004. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19005. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19006. serializationObject.type = this.getClassName();
  19007. // Parent
  19008. if (this.parent) {
  19009. serializationObject.parentId = this.parent.id;
  19010. }
  19011. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19012. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19013. }
  19014. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19015. serializationObject.isEnabled = this.isEnabled();
  19016. // Parent
  19017. if (this.parent) {
  19018. serializationObject.parentId = this.parent.id;
  19019. }
  19020. return serializationObject;
  19021. };
  19022. // Statics
  19023. /**
  19024. * Returns a new TransformNode object parsed from the source provided.
  19025. * The parameter `parsedMesh` is the source.
  19026. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19027. */
  19028. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19029. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19030. if (BABYLON.Tags) {
  19031. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19032. }
  19033. if (parsedTransformNode.localMatrix) {
  19034. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19035. }
  19036. else if (parsedTransformNode.pivotMatrix) {
  19037. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19038. }
  19039. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19040. // Parent
  19041. if (parsedTransformNode.parentId) {
  19042. transformNode._waitingParentId = parsedTransformNode.parentId;
  19043. }
  19044. return transformNode;
  19045. };
  19046. /**
  19047. * Releases resources associated with this transform node.
  19048. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19049. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19050. */
  19051. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19052. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19053. // Animations
  19054. this.getScene().stopAnimation(this);
  19055. // Remove from scene
  19056. this.getScene().removeTransformNode(this);
  19057. this.onAfterWorldMatrixUpdateObservable.clear();
  19058. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19059. };
  19060. // Statics
  19061. TransformNode.BILLBOARDMODE_NONE = 0;
  19062. TransformNode.BILLBOARDMODE_X = 1;
  19063. TransformNode.BILLBOARDMODE_Y = 2;
  19064. TransformNode.BILLBOARDMODE_Z = 4;
  19065. TransformNode.BILLBOARDMODE_ALL = 7;
  19066. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19067. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19068. __decorate([
  19069. BABYLON.serializeAsVector3()
  19070. ], TransformNode.prototype, "_rotation", void 0);
  19071. __decorate([
  19072. BABYLON.serializeAsQuaternion()
  19073. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19074. __decorate([
  19075. BABYLON.serializeAsVector3()
  19076. ], TransformNode.prototype, "_scaling", void 0);
  19077. __decorate([
  19078. BABYLON.serialize()
  19079. ], TransformNode.prototype, "billboardMode", void 0);
  19080. __decorate([
  19081. BABYLON.serialize()
  19082. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19083. __decorate([
  19084. BABYLON.serialize()
  19085. ], TransformNode.prototype, "infiniteDistance", void 0);
  19086. __decorate([
  19087. BABYLON.serializeAsVector3()
  19088. ], TransformNode.prototype, "position", void 0);
  19089. return TransformNode;
  19090. }(BABYLON.Node));
  19091. BABYLON.TransformNode = TransformNode;
  19092. })(BABYLON || (BABYLON = {}));
  19093. //# sourceMappingURL=babylon.transformNode.js.map
  19094. var BABYLON;
  19095. (function (BABYLON) {
  19096. var AbstractMesh = /** @class */ (function (_super) {
  19097. __extends(AbstractMesh, _super);
  19098. // Constructor
  19099. function AbstractMesh(name, scene) {
  19100. if (scene === void 0) { scene = null; }
  19101. var _this = _super.call(this, name, scene, false) || this;
  19102. _this._facetNb = 0; // facet number
  19103. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19104. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19105. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19106. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19107. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19108. _this._subDiv = {
  19109. max: 1,
  19110. X: 1,
  19111. Y: 1,
  19112. Z: 1
  19113. };
  19114. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19115. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19116. // Events
  19117. /**
  19118. * An event triggered when this mesh collides with another one
  19119. */
  19120. _this.onCollideObservable = new BABYLON.Observable();
  19121. /**
  19122. * An event triggered when the collision's position changes
  19123. */
  19124. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19125. /**
  19126. * An event triggered when material is changed
  19127. */
  19128. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19129. // Properties
  19130. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19131. /**
  19132. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19133. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19134. * or
  19135. * 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.
  19136. * for more info check WebGl documentations
  19137. */
  19138. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19139. /**
  19140. * 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:
  19141. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19142. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19143. * 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.
  19144. */
  19145. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19146. /**
  19147. * 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.
  19148. * The default value is -1 which means don't break the query and wait till the result.
  19149. */
  19150. _this.occlusionRetryCount = -1;
  19151. _this._occlusionInternalRetryCounter = 0;
  19152. _this._isOccluded = false;
  19153. _this._isOcclusionQueryInProgress = false;
  19154. _this._visibility = 1.0;
  19155. _this.alphaIndex = Number.MAX_VALUE;
  19156. _this.isVisible = true;
  19157. _this.isPickable = true;
  19158. _this.showBoundingBox = false;
  19159. _this.showSubMeshesBoundingBox = false;
  19160. _this.isBlocker = false;
  19161. _this.enablePointerMoveEvents = false;
  19162. _this.renderingGroupId = 0;
  19163. _this._receiveShadows = false;
  19164. _this.renderOutline = false;
  19165. _this.outlineColor = BABYLON.Color3.Red();
  19166. _this.outlineWidth = 0.02;
  19167. _this.renderOverlay = false;
  19168. _this.overlayColor = BABYLON.Color3.Red();
  19169. _this.overlayAlpha = 0.5;
  19170. _this._hasVertexAlpha = false;
  19171. _this._useVertexColors = true;
  19172. _this._computeBonesUsingShaders = true;
  19173. _this._numBoneInfluencers = 4;
  19174. _this._applyFog = true;
  19175. _this.useOctreeForRenderingSelection = true;
  19176. _this.useOctreeForPicking = true;
  19177. _this.useOctreeForCollisions = true;
  19178. _this._layerMask = 0x0FFFFFFF;
  19179. /**
  19180. * True if the mesh must be rendered in any case.
  19181. */
  19182. _this.alwaysSelectAsActiveMesh = false;
  19183. /**
  19184. * This scene's action manager
  19185. */
  19186. _this.actionManager = null;
  19187. // Physics
  19188. _this.physicsImpostor = null;
  19189. // Collisions
  19190. _this._checkCollisions = false;
  19191. _this._collisionMask = -1;
  19192. _this._collisionGroup = -1;
  19193. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19194. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19195. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19196. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19197. // Edges
  19198. _this.edgesWidth = 1;
  19199. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19200. // Cache
  19201. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19202. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19203. _this._renderId = 0;
  19204. _this._intersectionsInProgress = new Array();
  19205. _this._unIndexed = false;
  19206. _this._lightSources = new Array();
  19207. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19208. if (collidedMesh === void 0) { collidedMesh = null; }
  19209. //TODO move this to the collision coordinator!
  19210. if (_this.getScene().workerCollisions)
  19211. newPosition.multiplyInPlace(_this._collider._radius);
  19212. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19213. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19214. _this.position.addInPlace(_this._diffPositionForCollisions);
  19215. }
  19216. if (collidedMesh) {
  19217. _this.onCollideObservable.notifyObservers(collidedMesh);
  19218. }
  19219. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19220. };
  19221. _this.getScene().addMesh(_this);
  19222. _this._resyncLightSources();
  19223. return _this;
  19224. }
  19225. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19226. get: function () {
  19227. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19228. },
  19229. enumerable: true,
  19230. configurable: true
  19231. });
  19232. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19233. get: function () {
  19234. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19240. get: function () {
  19241. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19242. },
  19243. enumerable: true,
  19244. configurable: true
  19245. });
  19246. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19247. get: function () {
  19248. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19249. },
  19250. enumerable: true,
  19251. configurable: true
  19252. });
  19253. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19254. get: function () {
  19255. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19256. },
  19257. enumerable: true,
  19258. configurable: true
  19259. });
  19260. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19261. /**
  19262. * Read-only : the number of facets in the mesh
  19263. */
  19264. get: function () {
  19265. return this._facetNb;
  19266. },
  19267. enumerable: true,
  19268. configurable: true
  19269. });
  19270. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19271. /**
  19272. * The number (integer) of subdivisions per axis in the partioning space
  19273. */
  19274. get: function () {
  19275. return this._partitioningSubdivisions;
  19276. },
  19277. set: function (nb) {
  19278. this._partitioningSubdivisions = nb;
  19279. },
  19280. enumerable: true,
  19281. configurable: true
  19282. });
  19283. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19284. /**
  19285. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19286. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19287. */
  19288. get: function () {
  19289. return this._partitioningBBoxRatio;
  19290. },
  19291. set: function (ratio) {
  19292. this._partitioningBBoxRatio = ratio;
  19293. },
  19294. enumerable: true,
  19295. configurable: true
  19296. });
  19297. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19298. /**
  19299. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19300. * Works only for updatable meshes.
  19301. * Doesn't work with multi-materials.
  19302. */
  19303. get: function () {
  19304. return this._facetDepthSort;
  19305. },
  19306. set: function (sort) {
  19307. this._facetDepthSort = sort;
  19308. },
  19309. enumerable: true,
  19310. configurable: true
  19311. });
  19312. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19313. /**
  19314. * The location (Vector3) where the facet depth sort must be computed from.
  19315. * By default, the active camera position.
  19316. * Used only when facet depth sort is enabled.
  19317. */
  19318. get: function () {
  19319. return this._facetDepthSortFrom;
  19320. },
  19321. set: function (location) {
  19322. this._facetDepthSortFrom = location;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19328. /**
  19329. * Read-only boolean : is the feature facetData enabled ?
  19330. */
  19331. get: function () {
  19332. return this._facetDataEnabled;
  19333. },
  19334. enumerable: true,
  19335. configurable: true
  19336. });
  19337. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19338. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19339. return false;
  19340. }
  19341. this._markSubMeshesAsMiscDirty();
  19342. return true;
  19343. };
  19344. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19345. set: function (callback) {
  19346. if (this._onCollideObserver) {
  19347. this.onCollideObservable.remove(this._onCollideObserver);
  19348. }
  19349. this._onCollideObserver = this.onCollideObservable.add(callback);
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19355. set: function (callback) {
  19356. if (this._onCollisionPositionChangeObserver) {
  19357. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19358. }
  19359. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19365. /**
  19366. * 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.
  19367. */
  19368. get: function () {
  19369. return this._isOccluded;
  19370. },
  19371. set: function (value) {
  19372. this._isOccluded = value;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19378. /**
  19379. * Flag to check the progress status of the query
  19380. */
  19381. get: function () {
  19382. return this._isOcclusionQueryInProgress;
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19388. /**
  19389. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19390. */
  19391. get: function () {
  19392. return this._visibility;
  19393. },
  19394. /**
  19395. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19396. */
  19397. set: function (value) {
  19398. if (this._visibility === value) {
  19399. return;
  19400. }
  19401. this._visibility = value;
  19402. this._markSubMeshesAsMiscDirty();
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. Object.defineProperty(AbstractMesh.prototype, "material", {
  19408. get: function () {
  19409. return this._material;
  19410. },
  19411. set: function (value) {
  19412. if (this._material === value) {
  19413. return;
  19414. }
  19415. this._material = value;
  19416. if (this.onMaterialChangedObservable.hasObservers) {
  19417. this.onMaterialChangedObservable.notifyObservers(this);
  19418. }
  19419. if (!this.subMeshes) {
  19420. return;
  19421. }
  19422. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19423. var subMesh = _a[_i];
  19424. subMesh.setEffect(null);
  19425. }
  19426. },
  19427. enumerable: true,
  19428. configurable: true
  19429. });
  19430. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19431. get: function () {
  19432. return this._receiveShadows;
  19433. },
  19434. set: function (value) {
  19435. if (this._receiveShadows === value) {
  19436. return;
  19437. }
  19438. this._receiveShadows = value;
  19439. this._markSubMeshesAsLightDirty();
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19445. get: function () {
  19446. return this._hasVertexAlpha;
  19447. },
  19448. set: function (value) {
  19449. if (this._hasVertexAlpha === value) {
  19450. return;
  19451. }
  19452. this._hasVertexAlpha = value;
  19453. this._markSubMeshesAsAttributesDirty();
  19454. this._markSubMeshesAsMiscDirty();
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19460. get: function () {
  19461. return this._useVertexColors;
  19462. },
  19463. set: function (value) {
  19464. if (this._useVertexColors === value) {
  19465. return;
  19466. }
  19467. this._useVertexColors = value;
  19468. this._markSubMeshesAsAttributesDirty();
  19469. },
  19470. enumerable: true,
  19471. configurable: true
  19472. });
  19473. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19474. get: function () {
  19475. return this._computeBonesUsingShaders;
  19476. },
  19477. set: function (value) {
  19478. if (this._computeBonesUsingShaders === value) {
  19479. return;
  19480. }
  19481. this._computeBonesUsingShaders = value;
  19482. this._markSubMeshesAsAttributesDirty();
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19488. get: function () {
  19489. return this._numBoneInfluencers;
  19490. },
  19491. set: function (value) {
  19492. if (this._numBoneInfluencers === value) {
  19493. return;
  19494. }
  19495. this._numBoneInfluencers = value;
  19496. this._markSubMeshesAsAttributesDirty();
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19502. get: function () {
  19503. return this._applyFog;
  19504. },
  19505. set: function (value) {
  19506. if (this._applyFog === value) {
  19507. return;
  19508. }
  19509. this._applyFog = value;
  19510. this._markSubMeshesAsMiscDirty();
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19516. get: function () {
  19517. return this._layerMask;
  19518. },
  19519. set: function (value) {
  19520. if (value === this._layerMask) {
  19521. return;
  19522. }
  19523. this._layerMask = value;
  19524. this._resyncLightSources();
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19530. get: function () {
  19531. return this._collisionMask;
  19532. },
  19533. set: function (mask) {
  19534. this._collisionMask = !isNaN(mask) ? mask : -1;
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19540. get: function () {
  19541. return this._collisionGroup;
  19542. },
  19543. set: function (mask) {
  19544. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19550. get: function () {
  19551. return null;
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19557. get: function () {
  19558. return this._skeleton;
  19559. },
  19560. set: function (value) {
  19561. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19562. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19563. }
  19564. if (value && value.needInitialSkinMatrix) {
  19565. value._registerMeshWithPoseMatrix(this);
  19566. }
  19567. this._skeleton = value;
  19568. if (!this._skeleton) {
  19569. this._bonesTransformMatrices = null;
  19570. }
  19571. this._markSubMeshesAsAttributesDirty();
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. /**
  19577. * Returns the string "AbstractMesh"
  19578. */
  19579. AbstractMesh.prototype.getClassName = function () {
  19580. return "AbstractMesh";
  19581. };
  19582. /**
  19583. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19584. */
  19585. AbstractMesh.prototype.toString = function (fullDetails) {
  19586. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19587. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19588. if (this._skeleton) {
  19589. ret += ", skeleton: " + this._skeleton.name;
  19590. }
  19591. if (fullDetails) {
  19592. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19593. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19594. }
  19595. return ret;
  19596. };
  19597. AbstractMesh.prototype._rebuild = function () {
  19598. if (this._occlusionQuery) {
  19599. this._occlusionQuery = null;
  19600. }
  19601. if (this._edgesRenderer) {
  19602. this._edgesRenderer._rebuild();
  19603. }
  19604. if (!this.subMeshes) {
  19605. return;
  19606. }
  19607. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19608. var subMesh = _a[_i];
  19609. subMesh._rebuild();
  19610. }
  19611. };
  19612. AbstractMesh.prototype._resyncLightSources = function () {
  19613. this._lightSources.length = 0;
  19614. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19615. var light = _a[_i];
  19616. if (!light.isEnabled()) {
  19617. continue;
  19618. }
  19619. if (light.canAffectMesh(this)) {
  19620. this._lightSources.push(light);
  19621. }
  19622. }
  19623. this._markSubMeshesAsLightDirty();
  19624. };
  19625. AbstractMesh.prototype._resyncLighSource = function (light) {
  19626. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19627. var index = this._lightSources.indexOf(light);
  19628. if (index === -1) {
  19629. if (!isIn) {
  19630. return;
  19631. }
  19632. this._lightSources.push(light);
  19633. }
  19634. else {
  19635. if (isIn) {
  19636. return;
  19637. }
  19638. this._lightSources.splice(index, 1);
  19639. }
  19640. this._markSubMeshesAsLightDirty();
  19641. };
  19642. AbstractMesh.prototype._removeLightSource = function (light) {
  19643. var index = this._lightSources.indexOf(light);
  19644. if (index === -1) {
  19645. return;
  19646. }
  19647. this._lightSources.splice(index, 1);
  19648. this._markSubMeshesAsLightDirty();
  19649. };
  19650. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19651. if (!this.subMeshes) {
  19652. return;
  19653. }
  19654. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19655. var subMesh = _a[_i];
  19656. if (subMesh._materialDefines) {
  19657. func(subMesh._materialDefines);
  19658. }
  19659. }
  19660. };
  19661. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19662. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19663. };
  19664. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19665. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19666. };
  19667. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19668. if (!this.subMeshes) {
  19669. return;
  19670. }
  19671. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19672. var subMesh = _a[_i];
  19673. var material = subMesh.getMaterial();
  19674. if (material) {
  19675. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19676. }
  19677. }
  19678. };
  19679. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19680. /**
  19681. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19682. * Default : (1.0, 1.0, 1.0)
  19683. */
  19684. get: function () {
  19685. return this._scaling;
  19686. },
  19687. /**
  19688. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19689. * Default : (1.0, 1.0, 1.0)
  19690. */
  19691. set: function (newScaling) {
  19692. this._scaling = newScaling;
  19693. if (this.physicsImpostor) {
  19694. this.physicsImpostor.forceUpdate();
  19695. }
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. // Methods
  19701. /**
  19702. * Disables the mesh edger rendering mode.
  19703. * Returns the AbstractMesh.
  19704. */
  19705. AbstractMesh.prototype.disableEdgesRendering = function () {
  19706. if (this._edgesRenderer) {
  19707. this._edgesRenderer.dispose();
  19708. this._edgesRenderer = null;
  19709. }
  19710. return this;
  19711. };
  19712. /**
  19713. * Enables the edge rendering mode on the mesh.
  19714. * This mode makes the mesh edges visible.
  19715. * Returns the AbstractMesh.
  19716. */
  19717. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19718. if (epsilon === void 0) { epsilon = 0.95; }
  19719. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19720. this.disableEdgesRendering();
  19721. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19722. return this;
  19723. };
  19724. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19725. /**
  19726. * Returns true if the mesh is blocked. Used by the class Mesh.
  19727. * Returns the boolean `false` by default.
  19728. */
  19729. get: function () {
  19730. return false;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. /**
  19736. * Returns the mesh itself by default, used by the class Mesh.
  19737. * Returned type : AbstractMesh
  19738. */
  19739. AbstractMesh.prototype.getLOD = function (camera) {
  19740. return this;
  19741. };
  19742. /**
  19743. * Returns 0 by default, used by the class Mesh.
  19744. * Returns an integer.
  19745. */
  19746. AbstractMesh.prototype.getTotalVertices = function () {
  19747. return 0;
  19748. };
  19749. /**
  19750. * Returns null by default, used by the class Mesh.
  19751. * Returned type : integer array
  19752. */
  19753. AbstractMesh.prototype.getIndices = function () {
  19754. return null;
  19755. };
  19756. /**
  19757. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19758. * Returned type : float array or Float32Array
  19759. */
  19760. AbstractMesh.prototype.getVerticesData = function (kind) {
  19761. return null;
  19762. };
  19763. /**
  19764. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19765. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19766. * The `data` are either a numeric array either a Float32Array.
  19767. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19768. * 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).
  19769. * Note that a new underlying VertexBuffer object is created each call.
  19770. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19771. *
  19772. * Possible `kind` values :
  19773. * - BABYLON.VertexBuffer.PositionKind
  19774. * - BABYLON.VertexBuffer.UVKind
  19775. * - BABYLON.VertexBuffer.UV2Kind
  19776. * - BABYLON.VertexBuffer.UV3Kind
  19777. * - BABYLON.VertexBuffer.UV4Kind
  19778. * - BABYLON.VertexBuffer.UV5Kind
  19779. * - BABYLON.VertexBuffer.UV6Kind
  19780. * - BABYLON.VertexBuffer.ColorKind
  19781. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19782. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19783. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19784. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19785. *
  19786. * Returns the Mesh.
  19787. */
  19788. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19789. return this;
  19790. };
  19791. /**
  19792. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19793. * If the mesh has no geometry, it is simply returned as it is.
  19794. * The `data` are either a numeric array either a Float32Array.
  19795. * No new underlying VertexBuffer object is created.
  19796. * 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.
  19797. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19798. *
  19799. * Possible `kind` values :
  19800. * - BABYLON.VertexBuffer.PositionKind
  19801. * - BABYLON.VertexBuffer.UVKind
  19802. * - BABYLON.VertexBuffer.UV2Kind
  19803. * - BABYLON.VertexBuffer.UV3Kind
  19804. * - BABYLON.VertexBuffer.UV4Kind
  19805. * - BABYLON.VertexBuffer.UV5Kind
  19806. * - BABYLON.VertexBuffer.UV6Kind
  19807. * - BABYLON.VertexBuffer.ColorKind
  19808. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19809. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19810. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19811. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19812. *
  19813. * Returns the Mesh.
  19814. */
  19815. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19816. return this;
  19817. };
  19818. /**
  19819. * Sets the mesh indices.
  19820. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19821. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19822. * This method creates a new index buffer each call.
  19823. * Returns the Mesh.
  19824. */
  19825. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19826. return this;
  19827. };
  19828. /** Returns false by default, used by the class Mesh.
  19829. * Returns a boolean
  19830. */
  19831. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19832. return false;
  19833. };
  19834. /**
  19835. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19836. * Returns a BoundingInfo
  19837. */
  19838. AbstractMesh.prototype.getBoundingInfo = function () {
  19839. if (this._masterMesh) {
  19840. return this._masterMesh.getBoundingInfo();
  19841. }
  19842. if (!this._boundingInfo) {
  19843. // this._boundingInfo is being created here
  19844. this._updateBoundingInfo();
  19845. }
  19846. // cannot be null.
  19847. return this._boundingInfo;
  19848. };
  19849. /**
  19850. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19851. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19852. */
  19853. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19854. if (includeDescendants === void 0) { includeDescendants = true; }
  19855. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19856. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19857. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19858. if (maxDimension === 0) {
  19859. return this;
  19860. }
  19861. var scale = 1 / maxDimension;
  19862. this.scaling.scaleInPlace(scale);
  19863. return this;
  19864. };
  19865. /**
  19866. * Sets a mesh new object BoundingInfo.
  19867. * Returns the AbstractMesh.
  19868. */
  19869. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19870. this._boundingInfo = boundingInfo;
  19871. return this;
  19872. };
  19873. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19874. get: function () {
  19875. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. AbstractMesh.prototype._preActivate = function () {
  19881. };
  19882. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19883. };
  19884. AbstractMesh.prototype._activate = function (renderId) {
  19885. this._renderId = renderId;
  19886. };
  19887. /**
  19888. * Returns the latest update of the World matrix
  19889. * Returns a Matrix.
  19890. */
  19891. AbstractMesh.prototype.getWorldMatrix = function () {
  19892. if (this._masterMesh) {
  19893. return this._masterMesh.getWorldMatrix();
  19894. }
  19895. return _super.prototype.getWorldMatrix.call(this);
  19896. };
  19897. /**
  19898. * Returns the latest update of the World matrix determinant.
  19899. */
  19900. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19901. if (this._masterMesh) {
  19902. return this._masterMesh._getWorldMatrixDeterminant();
  19903. }
  19904. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19905. };
  19906. // ================================== Point of View Movement =================================
  19907. /**
  19908. * Perform relative position change from the point of view of behind the front of the mesh.
  19909. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19910. * Supports definition of mesh facing forward or backward.
  19911. * @param {number} amountRight
  19912. * @param {number} amountUp
  19913. * @param {number} amountForward
  19914. *
  19915. * Returns the AbstractMesh.
  19916. */
  19917. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19918. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19919. return this;
  19920. };
  19921. /**
  19922. * Calculate relative position change from the point of view of behind the front of the mesh.
  19923. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19924. * Supports definition of mesh facing forward or backward.
  19925. * @param {number} amountRight
  19926. * @param {number} amountUp
  19927. * @param {number} amountForward
  19928. *
  19929. * Returns a new Vector3.
  19930. */
  19931. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19932. var rotMatrix = new BABYLON.Matrix();
  19933. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19934. rotQuaternion.toRotationMatrix(rotMatrix);
  19935. var translationDelta = BABYLON.Vector3.Zero();
  19936. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19937. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19938. return translationDelta;
  19939. };
  19940. // ================================== Point of View Rotation =================================
  19941. /**
  19942. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19943. * Supports definition of mesh facing forward or backward.
  19944. * @param {number} flipBack
  19945. * @param {number} twirlClockwise
  19946. * @param {number} tiltRight
  19947. *
  19948. * Returns the AbstractMesh.
  19949. */
  19950. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19951. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19952. return this;
  19953. };
  19954. /**
  19955. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19956. * Supports definition of mesh facing forward or backward.
  19957. * @param {number} flipBack
  19958. * @param {number} twirlClockwise
  19959. * @param {number} tiltRight
  19960. *
  19961. * Returns a new Vector3.
  19962. */
  19963. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19964. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19965. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19966. };
  19967. /**
  19968. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19969. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19970. */
  19971. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19972. if (includeDescendants === void 0) { includeDescendants = true; }
  19973. this.computeWorldMatrix(true);
  19974. var min;
  19975. var max;
  19976. var boundingInfo = this.getBoundingInfo();
  19977. if (!this.subMeshes) {
  19978. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19979. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19980. }
  19981. else {
  19982. min = boundingInfo.boundingBox.minimumWorld;
  19983. max = boundingInfo.boundingBox.maximumWorld;
  19984. }
  19985. if (includeDescendants) {
  19986. var descendants = this.getDescendants(false);
  19987. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19988. var descendant = descendants_1[_i];
  19989. var childMesh = descendant;
  19990. childMesh.computeWorldMatrix(true);
  19991. //make sure we have the needed params to get mix and max
  19992. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19993. continue;
  19994. }
  19995. var childBoundingInfo = childMesh.getBoundingInfo();
  19996. var boundingBox = childBoundingInfo.boundingBox;
  19997. var minBox = boundingBox.minimumWorld;
  19998. var maxBox = boundingBox.maximumWorld;
  19999. BABYLON.Tools.CheckExtends(minBox, min, max);
  20000. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20001. }
  20002. }
  20003. return {
  20004. min: min,
  20005. max: max
  20006. };
  20007. };
  20008. /**
  20009. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  20010. * Returns the AbstractMesh.
  20011. */
  20012. AbstractMesh.prototype._updateBoundingInfo = function () {
  20013. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20014. this._boundingInfo.update(this.worldMatrixFromCache);
  20015. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20016. return this;
  20017. };
  20018. /**
  20019. * Update a mesh's children BoundingInfo objects only.
  20020. * Returns the AbstractMesh.
  20021. */
  20022. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20023. if (!this.subMeshes) {
  20024. return this;
  20025. }
  20026. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20027. var subMesh = this.subMeshes[subIndex];
  20028. if (!subMesh.IsGlobal) {
  20029. subMesh.updateBoundingInfo(matrix);
  20030. }
  20031. }
  20032. return this;
  20033. };
  20034. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20035. // Bounding info
  20036. this._updateBoundingInfo();
  20037. };
  20038. /**
  20039. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20040. * A mesh is in the frustum if its bounding box intersects the frustum.
  20041. * Boolean returned.
  20042. */
  20043. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20044. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20045. };
  20046. /**
  20047. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20048. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20049. * Boolean returned.
  20050. */
  20051. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20052. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20053. ;
  20054. };
  20055. /**
  20056. * True if the mesh intersects another mesh or a SolidParticle object.
  20057. * 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)
  20058. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20059. * Returns a boolean.
  20060. */
  20061. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20062. if (precise === void 0) { precise = false; }
  20063. if (!this._boundingInfo || !mesh._boundingInfo) {
  20064. return false;
  20065. }
  20066. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20067. return true;
  20068. }
  20069. if (includeDescendants) {
  20070. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20071. var child = _a[_i];
  20072. if (child.intersectsMesh(mesh, precise, true)) {
  20073. return true;
  20074. }
  20075. }
  20076. }
  20077. return false;
  20078. };
  20079. /**
  20080. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  20081. * Returns a boolean.
  20082. */
  20083. AbstractMesh.prototype.intersectsPoint = function (point) {
  20084. if (!this._boundingInfo) {
  20085. return false;
  20086. }
  20087. return this._boundingInfo.intersectsPoint(point);
  20088. };
  20089. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20090. return this.physicsImpostor;
  20091. };
  20092. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20093. if (camera === void 0) { camera = null; }
  20094. if (!camera) {
  20095. camera = this.getScene().activeCamera;
  20096. }
  20097. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20098. };
  20099. /**
  20100. * Returns the distance from the mesh to the active camera.
  20101. * Returns a float.
  20102. */
  20103. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20104. if (camera === void 0) { camera = null; }
  20105. if (!camera) {
  20106. camera = this.getScene().activeCamera;
  20107. }
  20108. return this.absolutePosition.subtract(camera.position).length();
  20109. };
  20110. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20111. if (!this.physicsImpostor) {
  20112. return this;
  20113. }
  20114. this.physicsImpostor.applyImpulse(force, contactPoint);
  20115. return this;
  20116. };
  20117. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20118. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20119. return this;
  20120. }
  20121. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20122. mainPivot: pivot1,
  20123. connectedPivot: pivot2,
  20124. nativeParams: options
  20125. });
  20126. return this;
  20127. };
  20128. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20129. // Collisions
  20130. /**
  20131. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20132. * Default `false`.
  20133. */
  20134. get: function () {
  20135. return this._checkCollisions;
  20136. },
  20137. set: function (collisionEnabled) {
  20138. this._checkCollisions = collisionEnabled;
  20139. if (this.getScene().workerCollisions) {
  20140. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20141. }
  20142. },
  20143. enumerable: true,
  20144. configurable: true
  20145. });
  20146. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20147. /**
  20148. * Gets Collider object used to compute collisions (not physics)
  20149. */
  20150. get: function () {
  20151. return this._collider;
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20157. var globalPosition = this.getAbsolutePosition();
  20158. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20159. if (!this._collider) {
  20160. this._collider = new BABYLON.Collider();
  20161. }
  20162. this._collider._radius = this.ellipsoid;
  20163. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20164. return this;
  20165. };
  20166. // Submeshes octree
  20167. /**
  20168. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20169. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20170. * Returns an Octree of submeshes.
  20171. */
  20172. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20173. if (maxCapacity === void 0) { maxCapacity = 64; }
  20174. if (maxDepth === void 0) { maxDepth = 2; }
  20175. if (!this._submeshesOctree) {
  20176. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20177. }
  20178. this.computeWorldMatrix(true);
  20179. var boundingInfo = this.getBoundingInfo();
  20180. // Update octree
  20181. var bbox = boundingInfo.boundingBox;
  20182. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20183. return this._submeshesOctree;
  20184. };
  20185. // Collisions
  20186. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20187. this._generatePointsArray();
  20188. if (!this._positions) {
  20189. return this;
  20190. }
  20191. // Transformation
  20192. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20193. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20194. subMesh._lastColliderWorldVertices = [];
  20195. subMesh._trianglePlanes = [];
  20196. var start = subMesh.verticesStart;
  20197. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20198. for (var i = start; i < end; i++) {
  20199. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20200. }
  20201. }
  20202. // Collide
  20203. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20204. if (collider.collisionFound) {
  20205. collider.collidedMesh = this;
  20206. }
  20207. return this;
  20208. };
  20209. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20210. var subMeshes;
  20211. var len;
  20212. // Octrees
  20213. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20214. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20215. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20216. len = intersections.length;
  20217. subMeshes = intersections.data;
  20218. }
  20219. else {
  20220. subMeshes = this.subMeshes;
  20221. len = subMeshes.length;
  20222. }
  20223. for (var index = 0; index < len; index++) {
  20224. var subMesh = subMeshes[index];
  20225. // Bounding test
  20226. if (len > 1 && !subMesh._checkCollision(collider))
  20227. continue;
  20228. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20229. }
  20230. return this;
  20231. };
  20232. AbstractMesh.prototype._checkCollision = function (collider) {
  20233. // Bounding box test
  20234. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20235. return this;
  20236. // Transformation matrix
  20237. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20238. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20239. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20240. return this;
  20241. };
  20242. // Picking
  20243. AbstractMesh.prototype._generatePointsArray = function () {
  20244. return false;
  20245. };
  20246. /**
  20247. * Checks if the passed Ray intersects with the mesh.
  20248. * Returns an object PickingInfo.
  20249. */
  20250. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20251. var pickingInfo = new BABYLON.PickingInfo();
  20252. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20253. return pickingInfo;
  20254. }
  20255. if (!this._generatePointsArray()) {
  20256. return pickingInfo;
  20257. }
  20258. var intersectInfo = null;
  20259. // Octrees
  20260. var subMeshes;
  20261. var len;
  20262. if (this._submeshesOctree && this.useOctreeForPicking) {
  20263. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20264. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20265. len = intersections.length;
  20266. subMeshes = intersections.data;
  20267. }
  20268. else {
  20269. subMeshes = this.subMeshes;
  20270. len = subMeshes.length;
  20271. }
  20272. for (var index = 0; index < len; index++) {
  20273. var subMesh = subMeshes[index];
  20274. // Bounding test
  20275. if (len > 1 && !subMesh.canIntersects(ray))
  20276. continue;
  20277. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20278. if (currentIntersectInfo) {
  20279. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20280. intersectInfo = currentIntersectInfo;
  20281. intersectInfo.subMeshId = index;
  20282. if (fastCheck) {
  20283. break;
  20284. }
  20285. }
  20286. }
  20287. }
  20288. if (intersectInfo) {
  20289. // Get picked point
  20290. var world = this.getWorldMatrix();
  20291. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20292. var direction = ray.direction.clone();
  20293. direction = direction.scale(intersectInfo.distance);
  20294. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20295. var pickedPoint = worldOrigin.add(worldDirection);
  20296. // Return result
  20297. pickingInfo.hit = true;
  20298. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20299. pickingInfo.pickedPoint = pickedPoint;
  20300. pickingInfo.pickedMesh = this;
  20301. pickingInfo.bu = intersectInfo.bu || 0;
  20302. pickingInfo.bv = intersectInfo.bv || 0;
  20303. pickingInfo.faceId = intersectInfo.faceId;
  20304. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20305. return pickingInfo;
  20306. }
  20307. return pickingInfo;
  20308. };
  20309. /**
  20310. * Clones the mesh, used by the class Mesh.
  20311. * Just returns `null` for an AbstractMesh.
  20312. */
  20313. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20314. return null;
  20315. };
  20316. /**
  20317. * Disposes all the mesh submeshes.
  20318. * Returns the AbstractMesh.
  20319. */
  20320. AbstractMesh.prototype.releaseSubMeshes = function () {
  20321. if (this.subMeshes) {
  20322. while (this.subMeshes.length) {
  20323. this.subMeshes[0].dispose();
  20324. }
  20325. }
  20326. else {
  20327. this.subMeshes = new Array();
  20328. }
  20329. return this;
  20330. };
  20331. /**
  20332. * Releases resources associated with this abstract mesh.
  20333. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20334. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20335. */
  20336. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20337. var _this = this;
  20338. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20339. var index;
  20340. // Smart Array Retainers.
  20341. this.getScene().freeActiveMeshes();
  20342. this.getScene().freeRenderingGroups();
  20343. // Action manager
  20344. if (this.actionManager !== undefined && this.actionManager !== null) {
  20345. this.actionManager.dispose();
  20346. this.actionManager = null;
  20347. }
  20348. // Skeleton
  20349. this._skeleton = null;
  20350. // Physics
  20351. if (this.physicsImpostor) {
  20352. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20353. }
  20354. // Intersections in progress
  20355. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20356. var other = this._intersectionsInProgress[index];
  20357. var pos = other._intersectionsInProgress.indexOf(this);
  20358. other._intersectionsInProgress.splice(pos, 1);
  20359. }
  20360. this._intersectionsInProgress = [];
  20361. // Lights
  20362. var lights = this.getScene().lights;
  20363. lights.forEach(function (light) {
  20364. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20365. if (meshIndex !== -1) {
  20366. light.includedOnlyMeshes.splice(meshIndex, 1);
  20367. }
  20368. meshIndex = light.excludedMeshes.indexOf(_this);
  20369. if (meshIndex !== -1) {
  20370. light.excludedMeshes.splice(meshIndex, 1);
  20371. }
  20372. // Shadow generators
  20373. var generator = light.getShadowGenerator();
  20374. if (generator) {
  20375. var shadowMap = generator.getShadowMap();
  20376. if (shadowMap && shadowMap.renderList) {
  20377. meshIndex = shadowMap.renderList.indexOf(_this);
  20378. if (meshIndex !== -1) {
  20379. shadowMap.renderList.splice(meshIndex, 1);
  20380. }
  20381. }
  20382. }
  20383. });
  20384. // Edges
  20385. if (this._edgesRenderer) {
  20386. this._edgesRenderer.dispose();
  20387. this._edgesRenderer = null;
  20388. }
  20389. // SubMeshes
  20390. if (this.getClassName() !== "InstancedMesh") {
  20391. this.releaseSubMeshes();
  20392. }
  20393. // Octree
  20394. var sceneOctree = this.getScene().selectionOctree;
  20395. if (sceneOctree !== undefined && sceneOctree !== null) {
  20396. var index = sceneOctree.dynamicContent.indexOf(this);
  20397. if (index !== -1) {
  20398. sceneOctree.dynamicContent.splice(index, 1);
  20399. }
  20400. }
  20401. // Query
  20402. var engine = this.getScene().getEngine();
  20403. if (this._occlusionQuery) {
  20404. this._isOcclusionQueryInProgress = false;
  20405. engine.deleteQuery(this._occlusionQuery);
  20406. this._occlusionQuery = null;
  20407. }
  20408. // Engine
  20409. engine.wipeCaches();
  20410. // Remove from scene
  20411. this.getScene().removeMesh(this);
  20412. if (disposeMaterialAndTextures) {
  20413. if (this.material) {
  20414. this.material.dispose(false, true);
  20415. }
  20416. }
  20417. if (!doNotRecurse) {
  20418. // Particles
  20419. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20420. if (this.getScene().particleSystems[index].emitter === this) {
  20421. this.getScene().particleSystems[index].dispose();
  20422. index--;
  20423. }
  20424. }
  20425. }
  20426. // facet data
  20427. if (this._facetDataEnabled) {
  20428. this.disableFacetData();
  20429. }
  20430. this.onAfterWorldMatrixUpdateObservable.clear();
  20431. this.onCollideObservable.clear();
  20432. this.onCollisionPositionChangeObservable.clear();
  20433. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20434. };
  20435. /**
  20436. * Adds the passed mesh as a child to the current mesh.
  20437. * Returns the AbstractMesh.
  20438. */
  20439. AbstractMesh.prototype.addChild = function (mesh) {
  20440. mesh.setParent(this);
  20441. return this;
  20442. };
  20443. /**
  20444. * Removes the passed mesh from the current mesh children list.
  20445. * Returns the AbstractMesh.
  20446. */
  20447. AbstractMesh.prototype.removeChild = function (mesh) {
  20448. mesh.setParent(null);
  20449. return this;
  20450. };
  20451. // Facet data
  20452. /**
  20453. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20454. * Returns the AbstractMesh.
  20455. */
  20456. AbstractMesh.prototype._initFacetData = function () {
  20457. if (!this._facetNormals) {
  20458. this._facetNormals = new Array();
  20459. }
  20460. if (!this._facetPositions) {
  20461. this._facetPositions = new Array();
  20462. }
  20463. if (!this._facetPartitioning) {
  20464. this._facetPartitioning = new Array();
  20465. }
  20466. this._facetNb = (this.getIndices().length / 3) | 0;
  20467. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20468. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20469. for (var f = 0; f < this._facetNb; f++) {
  20470. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20471. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20472. }
  20473. this._facetDataEnabled = true;
  20474. return this;
  20475. };
  20476. /**
  20477. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20478. * This method can be called within the render loop.
  20479. * 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.
  20480. * Returns the AbstractMesh.
  20481. */
  20482. AbstractMesh.prototype.updateFacetData = function () {
  20483. if (!this._facetDataEnabled) {
  20484. this._initFacetData();
  20485. }
  20486. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20487. var indices = this.getIndices();
  20488. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20489. var bInfo = this.getBoundingInfo();
  20490. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20491. // init arrays, matrix and sort function on first call
  20492. this._facetDepthSortEnabled = true;
  20493. if (indices instanceof Uint16Array) {
  20494. this._depthSortedIndices = new Uint16Array(indices);
  20495. }
  20496. else if (indices instanceof Uint32Array) {
  20497. this._depthSortedIndices = new Uint32Array(indices);
  20498. }
  20499. else {
  20500. var needs32bits = false;
  20501. for (var i = 0; i < indices.length; i++) {
  20502. if (indices[i] > 65535) {
  20503. needs32bits = true;
  20504. break;
  20505. }
  20506. }
  20507. if (needs32bits) {
  20508. this._depthSortedIndices = new Uint32Array(indices);
  20509. }
  20510. else {
  20511. this._depthSortedIndices = new Uint16Array(indices);
  20512. }
  20513. }
  20514. this._facetDepthSortFunction = function (f1, f2) {
  20515. return (f2.sqDistance - f1.sqDistance);
  20516. };
  20517. if (!this._facetDepthSortFrom) {
  20518. var camera = this.getScene().activeCamera;
  20519. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20520. }
  20521. this._depthSortedFacets = [];
  20522. for (var f = 0; f < this._facetNb; f++) {
  20523. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20524. this._depthSortedFacets.push(depthSortedFacet);
  20525. }
  20526. this._invertedMatrix = BABYLON.Matrix.Identity();
  20527. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20528. }
  20529. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20530. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20531. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20532. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20533. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20534. this._subDiv.max = this._partitioningSubdivisions;
  20535. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20536. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20537. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20538. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20539. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20540. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20541. // set the parameters for ComputeNormals()
  20542. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20543. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20544. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20545. this._facetParameters.bInfo = bInfo;
  20546. this._facetParameters.bbSize = this._bbSize;
  20547. this._facetParameters.subDiv = this._subDiv;
  20548. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20549. this._facetParameters.depthSort = this._facetDepthSort;
  20550. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20551. this.computeWorldMatrix(true);
  20552. this._worldMatrix.invertToRef(this._invertedMatrix);
  20553. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20554. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20555. }
  20556. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20557. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20558. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20559. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20560. var l = (this._depthSortedIndices.length / 3) | 0;
  20561. for (var f = 0; f < l; f++) {
  20562. var sind = this._depthSortedFacets[f].ind;
  20563. this._depthSortedIndices[f * 3] = indices[sind];
  20564. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20565. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20566. }
  20567. this.updateIndices(this._depthSortedIndices);
  20568. }
  20569. return this;
  20570. };
  20571. /**
  20572. * Returns the facetLocalNormals array.
  20573. * The normals are expressed in the mesh local space.
  20574. */
  20575. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20576. if (!this._facetNormals) {
  20577. this.updateFacetData();
  20578. }
  20579. return this._facetNormals;
  20580. };
  20581. /**
  20582. * Returns the facetLocalPositions array.
  20583. * The facet positions are expressed in the mesh local space.
  20584. */
  20585. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20586. if (!this._facetPositions) {
  20587. this.updateFacetData();
  20588. }
  20589. return this._facetPositions;
  20590. };
  20591. /**
  20592. * Returns the facetLocalPartioning array.
  20593. */
  20594. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20595. if (!this._facetPartitioning) {
  20596. this.updateFacetData();
  20597. }
  20598. return this._facetPartitioning;
  20599. };
  20600. /**
  20601. * Returns the i-th facet position in the world system.
  20602. * This method allocates a new Vector3 per call.
  20603. */
  20604. AbstractMesh.prototype.getFacetPosition = function (i) {
  20605. var pos = BABYLON.Vector3.Zero();
  20606. this.getFacetPositionToRef(i, pos);
  20607. return pos;
  20608. };
  20609. /**
  20610. * Sets the reference Vector3 with the i-th facet position in the world system.
  20611. * Returns the AbstractMesh.
  20612. */
  20613. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20614. var localPos = (this.getFacetLocalPositions())[i];
  20615. var world = this.getWorldMatrix();
  20616. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20617. return this;
  20618. };
  20619. /**
  20620. * Returns the i-th facet normal in the world system.
  20621. * This method allocates a new Vector3 per call.
  20622. */
  20623. AbstractMesh.prototype.getFacetNormal = function (i) {
  20624. var norm = BABYLON.Vector3.Zero();
  20625. this.getFacetNormalToRef(i, norm);
  20626. return norm;
  20627. };
  20628. /**
  20629. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20630. * Returns the AbstractMesh.
  20631. */
  20632. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20633. var localNorm = (this.getFacetLocalNormals())[i];
  20634. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20635. return this;
  20636. };
  20637. /**
  20638. * 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).
  20639. */
  20640. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20641. var bInfo = this.getBoundingInfo();
  20642. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20643. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20644. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20645. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20646. return null;
  20647. }
  20648. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20649. };
  20650. /**
  20651. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20652. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20653. * 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.
  20654. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20655. * 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.
  20656. */
  20657. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20658. if (checkFace === void 0) { checkFace = false; }
  20659. if (facing === void 0) { facing = true; }
  20660. var world = this.getWorldMatrix();
  20661. var invMat = BABYLON.Tmp.Matrix[5];
  20662. world.invertToRef(invMat);
  20663. var invVect = BABYLON.Tmp.Vector3[8];
  20664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20665. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20666. if (projected) {
  20667. // tranform the local computed projected vector to world coordinates
  20668. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20669. }
  20670. return closest;
  20671. };
  20672. /**
  20673. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20674. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20675. * 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.
  20676. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20677. * 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.
  20678. */
  20679. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20680. if (checkFace === void 0) { checkFace = false; }
  20681. if (facing === void 0) { facing = true; }
  20682. var closest = null;
  20683. var tmpx = 0.0;
  20684. var tmpy = 0.0;
  20685. var tmpz = 0.0;
  20686. var d = 0.0; // tmp dot facet normal * facet position
  20687. var t0 = 0.0;
  20688. var projx = 0.0;
  20689. var projy = 0.0;
  20690. var projz = 0.0;
  20691. // Get all the facets in the same partitioning block than (x, y, z)
  20692. var facetPositions = this.getFacetLocalPositions();
  20693. var facetNormals = this.getFacetLocalNormals();
  20694. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20695. if (!facetsInBlock) {
  20696. return null;
  20697. }
  20698. // Get the closest facet to (x, y, z)
  20699. var shortest = Number.MAX_VALUE; // init distance vars
  20700. var tmpDistance = shortest;
  20701. var fib; // current facet in the block
  20702. var norm; // current facet normal
  20703. var p0; // current facet barycenter position
  20704. // loop on all the facets in the current partitioning block
  20705. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20706. fib = facetsInBlock[idx];
  20707. norm = facetNormals[fib];
  20708. p0 = facetPositions[fib];
  20709. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20710. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20711. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20712. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20713. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20714. projx = x + norm.x * t0;
  20715. projy = y + norm.y * t0;
  20716. projz = z + norm.z * t0;
  20717. tmpx = projx - x;
  20718. tmpy = projy - y;
  20719. tmpz = projz - z;
  20720. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20721. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20722. shortest = tmpDistance;
  20723. closest = fib;
  20724. if (projected) {
  20725. projected.x = projx;
  20726. projected.y = projy;
  20727. projected.z = projz;
  20728. }
  20729. }
  20730. }
  20731. }
  20732. return closest;
  20733. };
  20734. /**
  20735. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20736. */
  20737. AbstractMesh.prototype.getFacetDataParameters = function () {
  20738. return this._facetParameters;
  20739. };
  20740. /**
  20741. * Disables the feature FacetData and frees the related memory.
  20742. * Returns the AbstractMesh.
  20743. */
  20744. AbstractMesh.prototype.disableFacetData = function () {
  20745. if (this._facetDataEnabled) {
  20746. this._facetDataEnabled = false;
  20747. this._facetPositions = new Array();
  20748. this._facetNormals = new Array();
  20749. this._facetPartitioning = new Array();
  20750. this._facetParameters = null;
  20751. this._depthSortedIndices = new Uint32Array(0);
  20752. }
  20753. return this;
  20754. };
  20755. /**
  20756. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20757. * Returns the mesh.
  20758. */
  20759. AbstractMesh.prototype.updateIndices = function (indices) {
  20760. return this;
  20761. };
  20762. /**
  20763. * The mesh Geometry. Actually used by the Mesh object.
  20764. * Returns a blank geometry object.
  20765. */
  20766. /**
  20767. * Creates new normals data for the mesh.
  20768. * @param updatable.
  20769. */
  20770. AbstractMesh.prototype.createNormals = function (updatable) {
  20771. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20772. var indices = this.getIndices();
  20773. var normals;
  20774. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20775. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20776. }
  20777. else {
  20778. normals = [];
  20779. }
  20780. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20781. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20782. };
  20783. /**
  20784. * Align the mesh with a normal.
  20785. * Returns the mesh.
  20786. */
  20787. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20788. if (!upDirection) {
  20789. upDirection = BABYLON.Axis.Y;
  20790. }
  20791. var axisX = BABYLON.Tmp.Vector3[0];
  20792. var axisZ = BABYLON.Tmp.Vector3[1];
  20793. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20794. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20795. if (this.rotationQuaternion) {
  20796. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20797. }
  20798. else {
  20799. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20800. }
  20801. return this;
  20802. };
  20803. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20804. var engine = this.getEngine();
  20805. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20806. this._isOccluded = false;
  20807. return;
  20808. }
  20809. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20810. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20811. if (isOcclusionQueryAvailable) {
  20812. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20813. this._isOcclusionQueryInProgress = false;
  20814. this._occlusionInternalRetryCounter = 0;
  20815. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20816. }
  20817. else {
  20818. this._occlusionInternalRetryCounter++;
  20819. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20820. this._isOcclusionQueryInProgress = false;
  20821. this._occlusionInternalRetryCounter = 0;
  20822. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20823. // if strict continue the last state of the object.
  20824. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20825. }
  20826. else {
  20827. return;
  20828. }
  20829. }
  20830. }
  20831. var scene = this.getScene();
  20832. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20833. if (!this._occlusionQuery) {
  20834. this._occlusionQuery = engine.createQuery();
  20835. }
  20836. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20837. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20838. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20839. this._isOcclusionQueryInProgress = true;
  20840. };
  20841. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20842. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20843. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20844. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20845. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20846. return AbstractMesh;
  20847. }(BABYLON.TransformNode));
  20848. BABYLON.AbstractMesh = AbstractMesh;
  20849. })(BABYLON || (BABYLON = {}));
  20850. //# sourceMappingURL=babylon.abstractMesh.js.map
  20851. var BABYLON;
  20852. (function (BABYLON) {
  20853. /**
  20854. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20855. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20856. * 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.
  20857. */
  20858. var Light = /** @class */ (function (_super) {
  20859. __extends(Light, _super);
  20860. /**
  20861. * Creates a Light object in the scene.
  20862. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20863. * @param name The firendly name of the light
  20864. * @param scene The scene the light belongs too
  20865. */
  20866. function Light(name, scene) {
  20867. var _this = _super.call(this, name, scene) || this;
  20868. /**
  20869. * Diffuse gives the basic color to an object.
  20870. */
  20871. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20872. /**
  20873. * Specular produces a highlight color on an object.
  20874. * Note: This is note affecting PBR materials.
  20875. */
  20876. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20877. /**
  20878. * Strength of the light.
  20879. * Note: By default it is define in the framework own unit.
  20880. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20881. */
  20882. _this.intensity = 1.0;
  20883. /**
  20884. * Defines how far from the source the light is impacting in scene units.
  20885. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20886. */
  20887. _this.range = Number.MAX_VALUE;
  20888. /**
  20889. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20890. * of light.
  20891. */
  20892. _this._photometricScale = 1.0;
  20893. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20894. _this._radius = 0.00001;
  20895. /**
  20896. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20897. * exceeding the number allowed of the materials.
  20898. */
  20899. _this.renderPriority = 0;
  20900. /**
  20901. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20902. * the current shadow generator.
  20903. */
  20904. _this.shadowEnabled = true;
  20905. _this._excludeWithLayerMask = 0;
  20906. _this._includeOnlyWithLayerMask = 0;
  20907. _this._lightmapMode = 0;
  20908. /**
  20909. * @ignore Internal use only.
  20910. */
  20911. _this._excludedMeshesIds = new Array();
  20912. /**
  20913. * @ignore Internal use only.
  20914. */
  20915. _this._includedOnlyMeshesIds = new Array();
  20916. _this.getScene().addLight(_this);
  20917. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20918. _this._buildUniformLayout();
  20919. _this.includedOnlyMeshes = new Array();
  20920. _this.excludedMeshes = new Array();
  20921. _this._resyncMeshes();
  20922. return _this;
  20923. }
  20924. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20925. /**
  20926. * If every light affecting the material is in this lightmapMode,
  20927. * material.lightmapTexture adds or multiplies
  20928. * (depends on material.useLightmapAsShadowmap)
  20929. * after every other light calculations.
  20930. */
  20931. get: function () {
  20932. return Light._LIGHTMAP_DEFAULT;
  20933. },
  20934. enumerable: true,
  20935. configurable: true
  20936. });
  20937. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20938. /**
  20939. * material.lightmapTexture as only diffuse lighting from this light
  20940. * adds only specular lighting from this light
  20941. * adds dynamic shadows
  20942. */
  20943. get: function () {
  20944. return Light._LIGHTMAP_SPECULAR;
  20945. },
  20946. enumerable: true,
  20947. configurable: true
  20948. });
  20949. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20950. /**
  20951. * material.lightmapTexture as only lighting
  20952. * no light calculation from this light
  20953. * only adds dynamic shadows from this light
  20954. */
  20955. get: function () {
  20956. return Light._LIGHTMAP_SHADOWSONLY;
  20957. },
  20958. enumerable: true,
  20959. configurable: true
  20960. });
  20961. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20962. /**
  20963. * Each light type uses the default quantity according to its type:
  20964. * point/spot lights use luminous intensity
  20965. * directional lights use illuminance
  20966. */
  20967. get: function () {
  20968. return Light._INTENSITYMODE_AUTOMATIC;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20974. /**
  20975. * lumen (lm)
  20976. */
  20977. get: function () {
  20978. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20984. /**
  20985. * candela (lm/sr)
  20986. */
  20987. get: function () {
  20988. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20989. },
  20990. enumerable: true,
  20991. configurable: true
  20992. });
  20993. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20994. /**
  20995. * lux (lm/m^2)
  20996. */
  20997. get: function () {
  20998. return Light._INTENSITYMODE_ILLUMINANCE;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21004. /**
  21005. * nit (cd/m^2)
  21006. */
  21007. get: function () {
  21008. return Light._INTENSITYMODE_LUMINANCE;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21014. /**
  21015. * Light type const id of the point light.
  21016. */
  21017. get: function () {
  21018. return Light._LIGHTTYPEID_POINTLIGHT;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21024. /**
  21025. * Light type const id of the directional light.
  21026. */
  21027. get: function () {
  21028. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21029. },
  21030. enumerable: true,
  21031. configurable: true
  21032. });
  21033. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21034. /**
  21035. * Light type const id of the spot light.
  21036. */
  21037. get: function () {
  21038. return Light._LIGHTTYPEID_SPOTLIGHT;
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21044. /**
  21045. * Light type const id of the hemispheric light.
  21046. */
  21047. get: function () {
  21048. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. Object.defineProperty(Light.prototype, "intensityMode", {
  21054. /**
  21055. * Gets the photometric scale used to interpret the intensity.
  21056. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21057. */
  21058. get: function () {
  21059. return this._intensityMode;
  21060. },
  21061. /**
  21062. * Sets the photometric scale used to interpret the intensity.
  21063. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21064. */
  21065. set: function (value) {
  21066. this._intensityMode = value;
  21067. this._computePhotometricScale();
  21068. },
  21069. enumerable: true,
  21070. configurable: true
  21071. });
  21072. ;
  21073. ;
  21074. Object.defineProperty(Light.prototype, "radius", {
  21075. /**
  21076. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21077. */
  21078. get: function () {
  21079. return this._radius;
  21080. },
  21081. /**
  21082. * sets the light radius used by PBR Materials to simulate soft area lights.
  21083. */
  21084. set: function (value) {
  21085. this._radius = value;
  21086. this._computePhotometricScale();
  21087. },
  21088. enumerable: true,
  21089. configurable: true
  21090. });
  21091. ;
  21092. ;
  21093. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21094. /**
  21095. * Gets the only meshes impacted by this light.
  21096. */
  21097. get: function () {
  21098. return this._includedOnlyMeshes;
  21099. },
  21100. /**
  21101. * Sets the only meshes impacted by this light.
  21102. */
  21103. set: function (value) {
  21104. this._includedOnlyMeshes = value;
  21105. this._hookArrayForIncludedOnly(value);
  21106. },
  21107. enumerable: true,
  21108. configurable: true
  21109. });
  21110. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21111. /**
  21112. * Gets the meshes not impacted by this light.
  21113. */
  21114. get: function () {
  21115. return this._excludedMeshes;
  21116. },
  21117. /**
  21118. * Sets the meshes not impacted by this light.
  21119. */
  21120. set: function (value) {
  21121. this._excludedMeshes = value;
  21122. this._hookArrayForExcluded(value);
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21128. /**
  21129. * Gets the layer id use to find what meshes are not impacted by the light.
  21130. * Inactive if 0
  21131. */
  21132. get: function () {
  21133. return this._excludeWithLayerMask;
  21134. },
  21135. /**
  21136. * Sets the layer id use to find what meshes are not impacted by the light.
  21137. * Inactive if 0
  21138. */
  21139. set: function (value) {
  21140. this._excludeWithLayerMask = value;
  21141. this._resyncMeshes();
  21142. },
  21143. enumerable: true,
  21144. configurable: true
  21145. });
  21146. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21147. /**
  21148. * Gets the layer id use to find what meshes are impacted by the light.
  21149. * Inactive if 0
  21150. */
  21151. get: function () {
  21152. return this._includeOnlyWithLayerMask;
  21153. },
  21154. /**
  21155. * Sets the layer id use to find what meshes are impacted by the light.
  21156. * Inactive if 0
  21157. */
  21158. set: function (value) {
  21159. this._includeOnlyWithLayerMask = value;
  21160. this._resyncMeshes();
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Light.prototype, "lightmapMode", {
  21166. /**
  21167. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21168. */
  21169. get: function () {
  21170. return this._lightmapMode;
  21171. },
  21172. /**
  21173. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21174. */
  21175. set: function (value) {
  21176. if (this._lightmapMode === value) {
  21177. return;
  21178. }
  21179. this._lightmapMode = value;
  21180. this._markMeshesAsLightDirty();
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. /**
  21186. * Returns the string "Light".
  21187. * @returns the class name
  21188. */
  21189. Light.prototype.getClassName = function () {
  21190. return "Light";
  21191. };
  21192. /**
  21193. * Converts the light information to a readable string for debug purpose.
  21194. * @param fullDetails Supports for multiple levels of logging within scene loading
  21195. * @returns the human readable light info
  21196. */
  21197. Light.prototype.toString = function (fullDetails) {
  21198. var ret = "Name: " + this.name;
  21199. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21200. if (this.animations) {
  21201. for (var i = 0; i < this.animations.length; i++) {
  21202. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21203. }
  21204. }
  21205. if (fullDetails) {
  21206. }
  21207. return ret;
  21208. };
  21209. /**
  21210. * Set the enabled state of this node.
  21211. * @param value - the new enabled state
  21212. */
  21213. Light.prototype.setEnabled = function (value) {
  21214. _super.prototype.setEnabled.call(this, value);
  21215. this._resyncMeshes();
  21216. };
  21217. /**
  21218. * Returns the Light associated shadow generator if any.
  21219. * @return the associated shadow generator.
  21220. */
  21221. Light.prototype.getShadowGenerator = function () {
  21222. return this._shadowGenerator;
  21223. };
  21224. /**
  21225. * Returns a Vector3, the absolute light position in the World.
  21226. * @returns the world space position of the light
  21227. */
  21228. Light.prototype.getAbsolutePosition = function () {
  21229. return BABYLON.Vector3.Zero();
  21230. };
  21231. /**
  21232. * Specifies if the light will affect the passed mesh.
  21233. * @param mesh The mesh to test against the light
  21234. * @return true the mesh is affected otherwise, false.
  21235. */
  21236. Light.prototype.canAffectMesh = function (mesh) {
  21237. if (!mesh) {
  21238. return true;
  21239. }
  21240. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21241. return false;
  21242. }
  21243. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21244. return false;
  21245. }
  21246. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21247. return false;
  21248. }
  21249. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21250. return false;
  21251. }
  21252. return true;
  21253. };
  21254. /**
  21255. * Computes and Returns the light World matrix.
  21256. * @returns the world matrix
  21257. */
  21258. Light.prototype.getWorldMatrix = function () {
  21259. this._currentRenderId = this.getScene().getRenderId();
  21260. this._childRenderId = this._currentRenderId;
  21261. var worldMatrix = this._getWorldMatrix();
  21262. if (this.parent && this.parent.getWorldMatrix) {
  21263. if (!this._parentedWorldMatrix) {
  21264. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21265. }
  21266. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21267. this._markSyncedWithParent();
  21268. return this._parentedWorldMatrix;
  21269. }
  21270. return worldMatrix;
  21271. };
  21272. /**
  21273. * Sort function to order lights for rendering.
  21274. * @param a First Light object to compare to second.
  21275. * @param b Second Light object to compare first.
  21276. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21277. */
  21278. Light.CompareLightsPriority = function (a, b) {
  21279. //shadow-casting lights have priority over non-shadow-casting lights
  21280. //the renderPrioirty is a secondary sort criterion
  21281. if (a.shadowEnabled !== b.shadowEnabled) {
  21282. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21283. }
  21284. return b.renderPriority - a.renderPriority;
  21285. };
  21286. /**
  21287. * Releases resources associated with this node.
  21288. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21289. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21290. */
  21291. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21292. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21293. if (this._shadowGenerator) {
  21294. this._shadowGenerator.dispose();
  21295. this._shadowGenerator = null;
  21296. }
  21297. // Animations
  21298. this.getScene().stopAnimation(this);
  21299. // Remove from meshes
  21300. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21301. var mesh = _a[_i];
  21302. mesh._removeLightSource(this);
  21303. }
  21304. this._uniformBuffer.dispose();
  21305. // Remove from scene
  21306. this.getScene().removeLight(this);
  21307. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21308. };
  21309. /**
  21310. * Returns the light type ID (integer).
  21311. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21312. */
  21313. Light.prototype.getTypeID = function () {
  21314. return 0;
  21315. };
  21316. /**
  21317. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21318. * @returns the scaled intensity in intensity mode unit
  21319. */
  21320. Light.prototype.getScaledIntensity = function () {
  21321. return this._photometricScale * this.intensity;
  21322. };
  21323. /**
  21324. * Returns a new Light object, named "name", from the current one.
  21325. * @param name The name of the cloned light
  21326. * @returns the new created light
  21327. */
  21328. Light.prototype.clone = function (name) {
  21329. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21330. if (!constructor) {
  21331. return null;
  21332. }
  21333. return BABYLON.SerializationHelper.Clone(constructor, this);
  21334. };
  21335. /**
  21336. * Serializes the current light into a Serialization object.
  21337. * @returns the serialized object.
  21338. */
  21339. Light.prototype.serialize = function () {
  21340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21341. // Type
  21342. serializationObject.type = this.getTypeID();
  21343. // Parent
  21344. if (this.parent) {
  21345. serializationObject.parentId = this.parent.id;
  21346. }
  21347. // Inclusion / exclusions
  21348. if (this.excludedMeshes.length > 0) {
  21349. serializationObject.excludedMeshesIds = [];
  21350. this.excludedMeshes.forEach(function (mesh) {
  21351. serializationObject.excludedMeshesIds.push(mesh.id);
  21352. });
  21353. }
  21354. if (this.includedOnlyMeshes.length > 0) {
  21355. serializationObject.includedOnlyMeshesIds = [];
  21356. this.includedOnlyMeshes.forEach(function (mesh) {
  21357. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21358. });
  21359. }
  21360. // Animations
  21361. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21362. serializationObject.ranges = this.serializeAnimationRanges();
  21363. return serializationObject;
  21364. };
  21365. /**
  21366. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21367. * This new light is named "name" and added to the passed scene.
  21368. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21369. * @param name The friendly name of the light
  21370. * @param scene The scene the new light will belong to
  21371. * @returns the constructor function
  21372. */
  21373. Light.GetConstructorFromName = function (type, name, scene) {
  21374. switch (type) {
  21375. case 0:
  21376. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21377. case 1:
  21378. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21379. case 2:
  21380. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21381. case 3:
  21382. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21383. }
  21384. return null;
  21385. };
  21386. /**
  21387. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21388. * @param parsedLight The JSON representation of the light
  21389. * @param scene The scene to create the parsed light in
  21390. * @returns the created light after parsing
  21391. */
  21392. Light.Parse = function (parsedLight, scene) {
  21393. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21394. if (!constructor) {
  21395. return null;
  21396. }
  21397. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21398. // Inclusion / exclusions
  21399. if (parsedLight.excludedMeshesIds) {
  21400. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21401. }
  21402. if (parsedLight.includedOnlyMeshesIds) {
  21403. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21404. }
  21405. // Parent
  21406. if (parsedLight.parentId) {
  21407. light._waitingParentId = parsedLight.parentId;
  21408. }
  21409. // Animations
  21410. if (parsedLight.animations) {
  21411. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21412. var parsedAnimation = parsedLight.animations[animationIndex];
  21413. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21414. }
  21415. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21416. }
  21417. if (parsedLight.autoAnimate) {
  21418. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21419. }
  21420. return light;
  21421. };
  21422. Light.prototype._hookArrayForExcluded = function (array) {
  21423. var _this = this;
  21424. var oldPush = array.push;
  21425. array.push = function () {
  21426. var items = [];
  21427. for (var _i = 0; _i < arguments.length; _i++) {
  21428. items[_i] = arguments[_i];
  21429. }
  21430. var result = oldPush.apply(array, items);
  21431. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21432. var item = items_1[_a];
  21433. item._resyncLighSource(_this);
  21434. }
  21435. return result;
  21436. };
  21437. var oldSplice = array.splice;
  21438. array.splice = function (index, deleteCount) {
  21439. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21440. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21441. var item = deleted_1[_i];
  21442. item._resyncLighSource(_this);
  21443. }
  21444. return deleted;
  21445. };
  21446. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21447. var item = array_1[_i];
  21448. item._resyncLighSource(this);
  21449. }
  21450. };
  21451. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21452. var _this = this;
  21453. var oldPush = array.push;
  21454. array.push = function () {
  21455. var items = [];
  21456. for (var _i = 0; _i < arguments.length; _i++) {
  21457. items[_i] = arguments[_i];
  21458. }
  21459. var result = oldPush.apply(array, items);
  21460. _this._resyncMeshes();
  21461. return result;
  21462. };
  21463. var oldSplice = array.splice;
  21464. array.splice = function (index, deleteCount) {
  21465. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21466. _this._resyncMeshes();
  21467. return deleted;
  21468. };
  21469. this._resyncMeshes();
  21470. };
  21471. Light.prototype._resyncMeshes = function () {
  21472. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21473. var mesh = _a[_i];
  21474. mesh._resyncLighSource(this);
  21475. }
  21476. };
  21477. /**
  21478. * Forces the meshes to update their light related information in their rendering used effects
  21479. * @ignore Internal Use Only
  21480. */
  21481. Light.prototype._markMeshesAsLightDirty = function () {
  21482. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21483. var mesh = _a[_i];
  21484. if (mesh._lightSources.indexOf(this) !== -1) {
  21485. mesh._markSubMeshesAsLightDirty();
  21486. }
  21487. }
  21488. };
  21489. /**
  21490. * Recomputes the cached photometric scale if needed.
  21491. */
  21492. Light.prototype._computePhotometricScale = function () {
  21493. this._photometricScale = this._getPhotometricScale();
  21494. this.getScene().resetCachedMaterial();
  21495. };
  21496. /**
  21497. * Returns the Photometric Scale according to the light type and intensity mode.
  21498. */
  21499. Light.prototype._getPhotometricScale = function () {
  21500. var photometricScale = 0.0;
  21501. var lightTypeID = this.getTypeID();
  21502. //get photometric mode
  21503. var photometricMode = this.intensityMode;
  21504. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21505. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21506. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21507. }
  21508. else {
  21509. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21510. }
  21511. }
  21512. //compute photometric scale
  21513. switch (lightTypeID) {
  21514. case Light.LIGHTTYPEID_POINTLIGHT:
  21515. case Light.LIGHTTYPEID_SPOTLIGHT:
  21516. switch (photometricMode) {
  21517. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21518. photometricScale = 1.0 / (4.0 * Math.PI);
  21519. break;
  21520. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21521. photometricScale = 1.0;
  21522. break;
  21523. case Light.INTENSITYMODE_LUMINANCE:
  21524. photometricScale = this.radius * this.radius;
  21525. break;
  21526. }
  21527. break;
  21528. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21529. switch (photometricMode) {
  21530. case Light.INTENSITYMODE_ILLUMINANCE:
  21531. photometricScale = 1.0;
  21532. break;
  21533. case Light.INTENSITYMODE_LUMINANCE:
  21534. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21535. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21536. var apexAngleRadians = this.radius;
  21537. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21538. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21539. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21540. photometricScale = solidAngle;
  21541. break;
  21542. }
  21543. break;
  21544. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21545. // No fall off in hemisperic light.
  21546. photometricScale = 1.0;
  21547. break;
  21548. }
  21549. return photometricScale;
  21550. };
  21551. /**
  21552. * Reorder the light in the scene according to their defined priority.
  21553. * @ignore Internal Use Only
  21554. */
  21555. Light.prototype._reorderLightsInScene = function () {
  21556. var scene = this.getScene();
  21557. if (this._renderPriority != 0) {
  21558. scene.requireLightSorting = true;
  21559. }
  21560. this.getScene().sortLightsByPriority();
  21561. };
  21562. //lightmapMode Consts
  21563. Light._LIGHTMAP_DEFAULT = 0;
  21564. Light._LIGHTMAP_SPECULAR = 1;
  21565. Light._LIGHTMAP_SHADOWSONLY = 2;
  21566. // Intensity Mode Consts
  21567. Light._INTENSITYMODE_AUTOMATIC = 0;
  21568. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21569. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21570. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21571. Light._INTENSITYMODE_LUMINANCE = 4;
  21572. // Light types ids const.
  21573. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21574. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21575. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21576. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21577. __decorate([
  21578. BABYLON.serializeAsColor3()
  21579. ], Light.prototype, "diffuse", void 0);
  21580. __decorate([
  21581. BABYLON.serializeAsColor3()
  21582. ], Light.prototype, "specular", void 0);
  21583. __decorate([
  21584. BABYLON.serialize()
  21585. ], Light.prototype, "intensity", void 0);
  21586. __decorate([
  21587. BABYLON.serialize()
  21588. ], Light.prototype, "range", void 0);
  21589. __decorate([
  21590. BABYLON.serialize()
  21591. ], Light.prototype, "intensityMode", null);
  21592. __decorate([
  21593. BABYLON.serialize()
  21594. ], Light.prototype, "radius", null);
  21595. __decorate([
  21596. BABYLON.serialize()
  21597. ], Light.prototype, "_renderPriority", void 0);
  21598. __decorate([
  21599. BABYLON.expandToProperty("_reorderLightsInScene")
  21600. ], Light.prototype, "renderPriority", void 0);
  21601. __decorate([
  21602. BABYLON.serialize()
  21603. ], Light.prototype, "shadowEnabled", void 0);
  21604. __decorate([
  21605. BABYLON.serialize("excludeWithLayerMask")
  21606. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21607. __decorate([
  21608. BABYLON.serialize("includeOnlyWithLayerMask")
  21609. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21610. __decorate([
  21611. BABYLON.serialize("lightmapMode")
  21612. ], Light.prototype, "_lightmapMode", void 0);
  21613. return Light;
  21614. }(BABYLON.Node));
  21615. BABYLON.Light = Light;
  21616. })(BABYLON || (BABYLON = {}));
  21617. //# sourceMappingURL=babylon.light.js.map
  21618. var BABYLON;
  21619. (function (BABYLON) {
  21620. var Camera = /** @class */ (function (_super) {
  21621. __extends(Camera, _super);
  21622. function Camera(name, position, scene) {
  21623. var _this = _super.call(this, name, scene) || this;
  21624. /**
  21625. * The vector the camera should consider as up.
  21626. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21627. */
  21628. _this.upVector = BABYLON.Vector3.Up();
  21629. _this.orthoLeft = null;
  21630. _this.orthoRight = null;
  21631. _this.orthoBottom = null;
  21632. _this.orthoTop = null;
  21633. /**
  21634. * FOV is set in Radians. (default is 0.8)
  21635. */
  21636. _this.fov = 0.8;
  21637. _this.minZ = 1;
  21638. _this.maxZ = 10000.0;
  21639. _this.inertia = 0.9;
  21640. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21641. _this.isIntermediate = false;
  21642. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21643. /**
  21644. * Restricts the camera to viewing objects with the same layerMask.
  21645. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21646. */
  21647. _this.layerMask = 0x0FFFFFFF;
  21648. /**
  21649. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21650. */
  21651. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21652. // Camera rig members
  21653. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21654. _this._rigCameras = new Array();
  21655. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21656. _this._skipRendering = false;
  21657. _this.customRenderTargets = new Array();
  21658. // Observables
  21659. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21660. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21661. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21662. _this.onRestoreStateObservable = new BABYLON.Observable();
  21663. // Cache
  21664. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21665. _this._projectionMatrix = new BABYLON.Matrix();
  21666. _this._doNotComputeProjectionMatrix = false;
  21667. _this._postProcesses = new Array();
  21668. _this._transformMatrix = BABYLON.Matrix.Zero();
  21669. _this._activeMeshes = new BABYLON.SmartArray(256);
  21670. _this._globalPosition = BABYLON.Vector3.Zero();
  21671. _this._refreshFrustumPlanes = true;
  21672. _this.getScene().addCamera(_this);
  21673. if (!_this.getScene().activeCamera) {
  21674. _this.getScene().activeCamera = _this;
  21675. }
  21676. _this.position = position;
  21677. return _this;
  21678. }
  21679. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21680. get: function () {
  21681. return Camera._PERSPECTIVE_CAMERA;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21687. get: function () {
  21688. return Camera._ORTHOGRAPHIC_CAMERA;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21694. /**
  21695. * This is the default FOV mode for perspective cameras.
  21696. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21697. *
  21698. */
  21699. get: function () {
  21700. return Camera._FOVMODE_VERTICAL_FIXED;
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21706. /**
  21707. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21708. *
  21709. */
  21710. get: function () {
  21711. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21712. },
  21713. enumerable: true,
  21714. configurable: true
  21715. });
  21716. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21717. get: function () {
  21718. return Camera._RIG_MODE_NONE;
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21724. get: function () {
  21725. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21726. },
  21727. enumerable: true,
  21728. configurable: true
  21729. });
  21730. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21731. get: function () {
  21732. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21733. },
  21734. enumerable: true,
  21735. configurable: true
  21736. });
  21737. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21738. get: function () {
  21739. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21740. },
  21741. enumerable: true,
  21742. configurable: true
  21743. });
  21744. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21745. get: function () {
  21746. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21752. get: function () {
  21753. return Camera._RIG_MODE_VR;
  21754. },
  21755. enumerable: true,
  21756. configurable: true
  21757. });
  21758. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21759. get: function () {
  21760. return Camera._RIG_MODE_WEBVR;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. /**
  21766. * Store current camera state (fov, position, etc..)
  21767. */
  21768. Camera.prototype.storeState = function () {
  21769. this._stateStored = true;
  21770. this._storedFov = this.fov;
  21771. return this;
  21772. };
  21773. /**
  21774. * Restores the camera state values if it has been stored. You must call storeState() first
  21775. */
  21776. Camera.prototype._restoreStateValues = function () {
  21777. if (!this._stateStored) {
  21778. return false;
  21779. }
  21780. this.fov = this._storedFov;
  21781. return true;
  21782. };
  21783. /**
  21784. * Restored camera state. You must call storeState() first
  21785. */
  21786. Camera.prototype.restoreState = function () {
  21787. if (this._restoreStateValues()) {
  21788. this.onRestoreStateObservable.notifyObservers(this);
  21789. return true;
  21790. }
  21791. return false;
  21792. };
  21793. Camera.prototype.getClassName = function () {
  21794. return "Camera";
  21795. };
  21796. /**
  21797. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21798. */
  21799. Camera.prototype.toString = function (fullDetails) {
  21800. var ret = "Name: " + this.name;
  21801. ret += ", type: " + this.getClassName();
  21802. if (this.animations) {
  21803. for (var i = 0; i < this.animations.length; i++) {
  21804. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21805. }
  21806. }
  21807. if (fullDetails) {
  21808. }
  21809. return ret;
  21810. };
  21811. Object.defineProperty(Camera.prototype, "globalPosition", {
  21812. get: function () {
  21813. return this._globalPosition;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Camera.prototype.getActiveMeshes = function () {
  21819. return this._activeMeshes;
  21820. };
  21821. Camera.prototype.isActiveMesh = function (mesh) {
  21822. return (this._activeMeshes.indexOf(mesh) !== -1);
  21823. };
  21824. /**
  21825. * Is this camera ready to be used/rendered
  21826. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21827. * @return true if the camera is ready
  21828. */
  21829. Camera.prototype.isReady = function (completeCheck) {
  21830. if (completeCheck === void 0) { completeCheck = false; }
  21831. if (completeCheck) {
  21832. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21833. var pp = _a[_i];
  21834. if (pp && !pp.isReady()) {
  21835. return false;
  21836. }
  21837. }
  21838. }
  21839. return _super.prototype.isReady.call(this, completeCheck);
  21840. };
  21841. //Cache
  21842. Camera.prototype._initCache = function () {
  21843. _super.prototype._initCache.call(this);
  21844. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21845. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21846. this._cache.mode = undefined;
  21847. this._cache.minZ = undefined;
  21848. this._cache.maxZ = undefined;
  21849. this._cache.fov = undefined;
  21850. this._cache.fovMode = undefined;
  21851. this._cache.aspectRatio = undefined;
  21852. this._cache.orthoLeft = undefined;
  21853. this._cache.orthoRight = undefined;
  21854. this._cache.orthoBottom = undefined;
  21855. this._cache.orthoTop = undefined;
  21856. this._cache.renderWidth = undefined;
  21857. this._cache.renderHeight = undefined;
  21858. };
  21859. Camera.prototype._updateCache = function (ignoreParentClass) {
  21860. if (!ignoreParentClass) {
  21861. _super.prototype._updateCache.call(this);
  21862. }
  21863. this._cache.position.copyFrom(this.position);
  21864. this._cache.upVector.copyFrom(this.upVector);
  21865. };
  21866. // Synchronized
  21867. Camera.prototype._isSynchronized = function () {
  21868. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21869. };
  21870. Camera.prototype._isSynchronizedViewMatrix = function () {
  21871. if (!_super.prototype._isSynchronized.call(this))
  21872. return false;
  21873. return this._cache.position.equals(this.position)
  21874. && this._cache.upVector.equals(this.upVector)
  21875. && this.isSynchronizedWithParent();
  21876. };
  21877. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21878. var check = this._cache.mode === this.mode
  21879. && this._cache.minZ === this.minZ
  21880. && this._cache.maxZ === this.maxZ;
  21881. if (!check) {
  21882. return false;
  21883. }
  21884. var engine = this.getEngine();
  21885. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21886. check = this._cache.fov === this.fov
  21887. && this._cache.fovMode === this.fovMode
  21888. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21889. }
  21890. else {
  21891. check = this._cache.orthoLeft === this.orthoLeft
  21892. && this._cache.orthoRight === this.orthoRight
  21893. && this._cache.orthoBottom === this.orthoBottom
  21894. && this._cache.orthoTop === this.orthoTop
  21895. && this._cache.renderWidth === engine.getRenderWidth()
  21896. && this._cache.renderHeight === engine.getRenderHeight();
  21897. }
  21898. return check;
  21899. };
  21900. // Controls
  21901. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21902. };
  21903. Camera.prototype.detachControl = function (element) {
  21904. };
  21905. Camera.prototype.update = function () {
  21906. this._checkInputs();
  21907. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21908. this._updateRigCameras();
  21909. }
  21910. };
  21911. Camera.prototype._checkInputs = function () {
  21912. this.onAfterCheckInputsObservable.notifyObservers(this);
  21913. };
  21914. Object.defineProperty(Camera.prototype, "rigCameras", {
  21915. get: function () {
  21916. return this._rigCameras;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21922. get: function () {
  21923. return this._rigPostProcess;
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. /**
  21929. * Internal, gets the first post proces.
  21930. * @returns the first post process to be run on this camera.
  21931. */
  21932. Camera.prototype._getFirstPostProcess = function () {
  21933. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21934. if (this._postProcesses[ppIndex] !== null) {
  21935. return this._postProcesses[ppIndex];
  21936. }
  21937. }
  21938. return null;
  21939. };
  21940. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21941. // invalidate framebuffer
  21942. var firstPostProcess = this._getFirstPostProcess();
  21943. if (firstPostProcess) {
  21944. firstPostProcess.markTextureDirty();
  21945. }
  21946. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21947. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21948. var cam = this._rigCameras[i];
  21949. var rigPostProcess = cam._rigPostProcess;
  21950. // for VR rig, there does not have to be a post process
  21951. if (rigPostProcess) {
  21952. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21953. if (isPass) {
  21954. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21955. cam.isIntermediate = this._postProcesses.length === 0;
  21956. }
  21957. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21958. rigPostProcess.markTextureDirty();
  21959. }
  21960. else {
  21961. cam._postProcesses = this._postProcesses.slice(0);
  21962. }
  21963. }
  21964. };
  21965. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21966. if (insertAt === void 0) { insertAt = null; }
  21967. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21968. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21969. return 0;
  21970. }
  21971. if (insertAt == null || insertAt < 0) {
  21972. this._postProcesses.push(postProcess);
  21973. }
  21974. else if (this._postProcesses[insertAt] === null) {
  21975. this._postProcesses[insertAt] = postProcess;
  21976. }
  21977. else {
  21978. this._postProcesses.splice(insertAt, 0, postProcess);
  21979. }
  21980. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21981. return this._postProcesses.indexOf(postProcess);
  21982. };
  21983. Camera.prototype.detachPostProcess = function (postProcess) {
  21984. var idx = this._postProcesses.indexOf(postProcess);
  21985. if (idx !== -1) {
  21986. this._postProcesses[idx] = null;
  21987. }
  21988. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21989. };
  21990. Camera.prototype.getWorldMatrix = function () {
  21991. if (!this._worldMatrix) {
  21992. this._worldMatrix = BABYLON.Matrix.Identity();
  21993. }
  21994. var viewMatrix = this.getViewMatrix();
  21995. viewMatrix.invertToRef(this._worldMatrix);
  21996. return this._worldMatrix;
  21997. };
  21998. Camera.prototype._getViewMatrix = function () {
  21999. return BABYLON.Matrix.Identity();
  22000. };
  22001. Camera.prototype.getViewMatrix = function (force) {
  22002. if (!force && this._isSynchronizedViewMatrix()) {
  22003. return this._computedViewMatrix;
  22004. }
  22005. this.updateCache();
  22006. this._computedViewMatrix = this._getViewMatrix();
  22007. this._currentRenderId = this.getScene().getRenderId();
  22008. this._childRenderId = this._currentRenderId;
  22009. this._refreshFrustumPlanes = true;
  22010. if (!this.parent || !this.parent.getWorldMatrix) {
  22011. this._globalPosition.copyFrom(this.position);
  22012. }
  22013. else {
  22014. if (!this._worldMatrix) {
  22015. this._worldMatrix = BABYLON.Matrix.Identity();
  22016. }
  22017. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22018. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22019. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22020. this._computedViewMatrix.invert();
  22021. this._markSyncedWithParent();
  22022. }
  22023. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22024. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22025. }
  22026. this.onViewMatrixChangedObservable.notifyObservers(this);
  22027. return this._computedViewMatrix;
  22028. };
  22029. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22030. this._doNotComputeProjectionMatrix = true;
  22031. if (projection !== undefined) {
  22032. this._projectionMatrix = projection;
  22033. }
  22034. };
  22035. ;
  22036. Camera.prototype.unfreezeProjectionMatrix = function () {
  22037. this._doNotComputeProjectionMatrix = false;
  22038. };
  22039. ;
  22040. Camera.prototype.getProjectionMatrix = function (force) {
  22041. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22042. return this._projectionMatrix;
  22043. }
  22044. // Cache
  22045. this._cache.mode = this.mode;
  22046. this._cache.minZ = this.minZ;
  22047. this._cache.maxZ = this.maxZ;
  22048. // Matrix
  22049. this._refreshFrustumPlanes = true;
  22050. var engine = this.getEngine();
  22051. var scene = this.getScene();
  22052. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22053. this._cache.fov = this.fov;
  22054. this._cache.fovMode = this.fovMode;
  22055. this._cache.aspectRatio = engine.getAspectRatio(this);
  22056. if (this.minZ <= 0) {
  22057. this.minZ = 0.1;
  22058. }
  22059. if (scene.useRightHandedSystem) {
  22060. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22061. }
  22062. else {
  22063. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22064. }
  22065. }
  22066. else {
  22067. var halfWidth = engine.getRenderWidth() / 2.0;
  22068. var halfHeight = engine.getRenderHeight() / 2.0;
  22069. if (scene.useRightHandedSystem) {
  22070. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22071. }
  22072. else {
  22073. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22074. }
  22075. this._cache.orthoLeft = this.orthoLeft;
  22076. this._cache.orthoRight = this.orthoRight;
  22077. this._cache.orthoBottom = this.orthoBottom;
  22078. this._cache.orthoTop = this.orthoTop;
  22079. this._cache.renderWidth = engine.getRenderWidth();
  22080. this._cache.renderHeight = engine.getRenderHeight();
  22081. }
  22082. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22083. return this._projectionMatrix;
  22084. };
  22085. Camera.prototype.getTranformationMatrix = function () {
  22086. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22087. return this._transformMatrix;
  22088. };
  22089. Camera.prototype.updateFrustumPlanes = function () {
  22090. if (!this._refreshFrustumPlanes) {
  22091. return;
  22092. }
  22093. this.getTranformationMatrix();
  22094. if (!this._frustumPlanes) {
  22095. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22096. }
  22097. else {
  22098. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22099. }
  22100. this._refreshFrustumPlanes = false;
  22101. };
  22102. Camera.prototype.isInFrustum = function (target) {
  22103. this.updateFrustumPlanes();
  22104. return target.isInFrustum(this._frustumPlanes);
  22105. };
  22106. Camera.prototype.isCompletelyInFrustum = function (target) {
  22107. this.updateFrustumPlanes();
  22108. return target.isCompletelyInFrustum(this._frustumPlanes);
  22109. };
  22110. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22111. if (length === void 0) { length = 100; }
  22112. if (!transform) {
  22113. transform = this.getWorldMatrix();
  22114. }
  22115. if (!origin) {
  22116. origin = this.position;
  22117. }
  22118. var forward = new BABYLON.Vector3(0, 0, 1);
  22119. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22120. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22121. return new BABYLON.Ray(origin, direction, length);
  22122. };
  22123. /**
  22124. * Releases resources associated with this node.
  22125. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22126. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22127. */
  22128. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22129. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22130. // Observables
  22131. this.onViewMatrixChangedObservable.clear();
  22132. this.onProjectionMatrixChangedObservable.clear();
  22133. this.onAfterCheckInputsObservable.clear();
  22134. this.onRestoreStateObservable.clear();
  22135. // Inputs
  22136. if (this.inputs) {
  22137. this.inputs.clear();
  22138. }
  22139. // Animations
  22140. this.getScene().stopAnimation(this);
  22141. // Remove from scene
  22142. this.getScene().removeCamera(this);
  22143. while (this._rigCameras.length > 0) {
  22144. var camera = this._rigCameras.pop();
  22145. if (camera) {
  22146. camera.dispose();
  22147. }
  22148. }
  22149. // Postprocesses
  22150. if (this._rigPostProcess) {
  22151. this._rigPostProcess.dispose(this);
  22152. this._rigPostProcess = null;
  22153. this._postProcesses = [];
  22154. }
  22155. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22156. this._rigPostProcess = null;
  22157. this._postProcesses = [];
  22158. }
  22159. else {
  22160. var i = this._postProcesses.length;
  22161. while (--i >= 0) {
  22162. var postProcess = this._postProcesses[i];
  22163. if (postProcess) {
  22164. postProcess.dispose(this);
  22165. }
  22166. }
  22167. }
  22168. // Render targets
  22169. var i = this.customRenderTargets.length;
  22170. while (--i >= 0) {
  22171. this.customRenderTargets[i].dispose();
  22172. }
  22173. this.customRenderTargets = [];
  22174. // Active Meshes
  22175. this._activeMeshes.dispose();
  22176. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22177. };
  22178. Object.defineProperty(Camera.prototype, "leftCamera", {
  22179. // ---- Camera rigs section ----
  22180. get: function () {
  22181. if (this._rigCameras.length < 1) {
  22182. return null;
  22183. }
  22184. return this._rigCameras[0];
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Camera.prototype, "rightCamera", {
  22190. get: function () {
  22191. if (this._rigCameras.length < 2) {
  22192. return null;
  22193. }
  22194. return this._rigCameras[1];
  22195. },
  22196. enumerable: true,
  22197. configurable: true
  22198. });
  22199. Camera.prototype.getLeftTarget = function () {
  22200. if (this._rigCameras.length < 1) {
  22201. return null;
  22202. }
  22203. return this._rigCameras[0].getTarget();
  22204. };
  22205. Camera.prototype.getRightTarget = function () {
  22206. if (this._rigCameras.length < 2) {
  22207. return null;
  22208. }
  22209. return this._rigCameras[1].getTarget();
  22210. };
  22211. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22212. if (this.cameraRigMode === mode) {
  22213. return;
  22214. }
  22215. while (this._rigCameras.length > 0) {
  22216. var camera = this._rigCameras.pop();
  22217. if (camera) {
  22218. camera.dispose();
  22219. }
  22220. }
  22221. this.cameraRigMode = mode;
  22222. this._cameraRigParams = {};
  22223. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22224. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22225. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22226. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22227. // create the rig cameras, unless none
  22228. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22229. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22230. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22231. if (leftCamera && rightCamera) {
  22232. this._rigCameras.push(leftCamera);
  22233. this._rigCameras.push(rightCamera);
  22234. }
  22235. }
  22236. switch (this.cameraRigMode) {
  22237. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22238. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22239. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22240. break;
  22241. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22242. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22243. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22244. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22245. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22246. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22247. break;
  22248. case Camera.RIG_MODE_VR:
  22249. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22250. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22251. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22252. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22253. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22254. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22255. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22256. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22257. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22258. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22259. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22260. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22261. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22262. if (metrics.compensateDistortion) {
  22263. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22264. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22265. }
  22266. break;
  22267. case Camera.RIG_MODE_WEBVR:
  22268. if (rigParams.vrDisplay) {
  22269. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22270. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22271. //Left eye
  22272. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22273. this._rigCameras[0].setCameraRigParameter("left", true);
  22274. //leaving this for future reference
  22275. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22276. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22277. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22278. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22279. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22280. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22281. this._rigCameras[0].parent = this;
  22282. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22283. //Right eye
  22284. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22285. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22286. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22287. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22288. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22289. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22290. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22291. this._rigCameras[1].parent = this;
  22292. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22293. if (Camera.UseAlternateWebVRRendering) {
  22294. this._rigCameras[1]._skipRendering = true;
  22295. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22296. }
  22297. }
  22298. break;
  22299. }
  22300. this._cascadePostProcessesToRigCams();
  22301. this.update();
  22302. };
  22303. Camera.prototype._getVRProjectionMatrix = function () {
  22304. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22305. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22306. return this._projectionMatrix;
  22307. };
  22308. Camera.prototype._updateCameraRotationMatrix = function () {
  22309. //Here for WebVR
  22310. };
  22311. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22312. //Here for WebVR
  22313. };
  22314. /**
  22315. * This function MUST be overwritten by the different WebVR cameras available.
  22316. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22317. */
  22318. Camera.prototype._getWebVRProjectionMatrix = function () {
  22319. return BABYLON.Matrix.Identity();
  22320. };
  22321. /**
  22322. * This function MUST be overwritten by the different WebVR cameras available.
  22323. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22324. */
  22325. Camera.prototype._getWebVRViewMatrix = function () {
  22326. return BABYLON.Matrix.Identity();
  22327. };
  22328. Camera.prototype.setCameraRigParameter = function (name, value) {
  22329. if (!this._cameraRigParams) {
  22330. this._cameraRigParams = {};
  22331. }
  22332. this._cameraRigParams[name] = value;
  22333. //provisionnally:
  22334. if (name === "interaxialDistance") {
  22335. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22336. }
  22337. };
  22338. /**
  22339. * needs to be overridden by children so sub has required properties to be copied
  22340. */
  22341. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22342. return null;
  22343. };
  22344. /**
  22345. * May need to be overridden by children
  22346. */
  22347. Camera.prototype._updateRigCameras = function () {
  22348. for (var i = 0; i < this._rigCameras.length; i++) {
  22349. this._rigCameras[i].minZ = this.minZ;
  22350. this._rigCameras[i].maxZ = this.maxZ;
  22351. this._rigCameras[i].fov = this.fov;
  22352. }
  22353. // only update viewport when ANAGLYPH
  22354. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22355. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22356. }
  22357. };
  22358. Camera.prototype._setupInputs = function () {
  22359. };
  22360. Camera.prototype.serialize = function () {
  22361. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22362. // Type
  22363. serializationObject.type = this.getClassName();
  22364. // Parent
  22365. if (this.parent) {
  22366. serializationObject.parentId = this.parent.id;
  22367. }
  22368. if (this.inputs) {
  22369. this.inputs.serialize(serializationObject);
  22370. }
  22371. // Animations
  22372. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22373. serializationObject.ranges = this.serializeAnimationRanges();
  22374. return serializationObject;
  22375. };
  22376. Camera.prototype.clone = function (name) {
  22377. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22378. };
  22379. Camera.prototype.getDirection = function (localAxis) {
  22380. var result = BABYLON.Vector3.Zero();
  22381. this.getDirectionToRef(localAxis, result);
  22382. return result;
  22383. };
  22384. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22385. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22386. };
  22387. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22388. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22389. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22390. switch (type) {
  22391. case "ArcRotateCamera":
  22392. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22393. case "DeviceOrientationCamera":
  22394. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22395. case "FollowCamera":
  22396. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22397. case "ArcFollowCamera":
  22398. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22399. case "GamepadCamera":
  22400. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22401. case "TouchCamera":
  22402. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22403. case "VirtualJoysticksCamera":
  22404. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22405. case "WebVRFreeCamera":
  22406. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22407. case "WebVRGamepadCamera":
  22408. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22409. case "VRDeviceOrientationFreeCamera":
  22410. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22411. case "VRDeviceOrientationGamepadCamera":
  22412. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22413. case "AnaglyphArcRotateCamera":
  22414. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22415. case "AnaglyphFreeCamera":
  22416. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22417. case "AnaglyphGamepadCamera":
  22418. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22419. case "AnaglyphUniversalCamera":
  22420. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22421. case "StereoscopicArcRotateCamera":
  22422. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22423. case "StereoscopicFreeCamera":
  22424. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22425. case "StereoscopicGamepadCamera":
  22426. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22427. case "StereoscopicUniversalCamera":
  22428. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22429. case "FreeCamera": // Forcing Universal here
  22430. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22431. default: // Universal Camera is the default value
  22432. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22433. }
  22434. };
  22435. Camera.prototype.computeWorldMatrix = function () {
  22436. return this.getWorldMatrix();
  22437. };
  22438. Camera.Parse = function (parsedCamera, scene) {
  22439. var type = parsedCamera.type;
  22440. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22441. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22442. // Parent
  22443. if (parsedCamera.parentId) {
  22444. camera._waitingParentId = parsedCamera.parentId;
  22445. }
  22446. //If camera has an input manager, let it parse inputs settings
  22447. if (camera.inputs) {
  22448. camera.inputs.parse(parsedCamera);
  22449. camera._setupInputs();
  22450. }
  22451. if (camera.setPosition) { // need to force position
  22452. camera.position.copyFromFloats(0, 0, 0);
  22453. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22454. }
  22455. // Target
  22456. if (parsedCamera.target) {
  22457. if (camera.setTarget) {
  22458. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22459. }
  22460. }
  22461. // Apply 3d rig, when found
  22462. if (parsedCamera.cameraRigMode) {
  22463. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22464. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22465. }
  22466. // Animations
  22467. if (parsedCamera.animations) {
  22468. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22469. var parsedAnimation = parsedCamera.animations[animationIndex];
  22470. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22471. }
  22472. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22473. }
  22474. if (parsedCamera.autoAnimate) {
  22475. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22476. }
  22477. return camera;
  22478. };
  22479. // Statics
  22480. Camera._PERSPECTIVE_CAMERA = 0;
  22481. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22482. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22483. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22484. Camera._RIG_MODE_NONE = 0;
  22485. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22486. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22487. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22488. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22489. Camera._RIG_MODE_VR = 20;
  22490. Camera._RIG_MODE_WEBVR = 21;
  22491. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22492. Camera.UseAlternateWebVRRendering = false;
  22493. __decorate([
  22494. BABYLON.serializeAsVector3()
  22495. ], Camera.prototype, "position", void 0);
  22496. __decorate([
  22497. BABYLON.serializeAsVector3()
  22498. ], Camera.prototype, "upVector", void 0);
  22499. __decorate([
  22500. BABYLON.serialize()
  22501. ], Camera.prototype, "orthoLeft", void 0);
  22502. __decorate([
  22503. BABYLON.serialize()
  22504. ], Camera.prototype, "orthoRight", void 0);
  22505. __decorate([
  22506. BABYLON.serialize()
  22507. ], Camera.prototype, "orthoBottom", void 0);
  22508. __decorate([
  22509. BABYLON.serialize()
  22510. ], Camera.prototype, "orthoTop", void 0);
  22511. __decorate([
  22512. BABYLON.serialize()
  22513. ], Camera.prototype, "fov", void 0);
  22514. __decorate([
  22515. BABYLON.serialize()
  22516. ], Camera.prototype, "minZ", void 0);
  22517. __decorate([
  22518. BABYLON.serialize()
  22519. ], Camera.prototype, "maxZ", void 0);
  22520. __decorate([
  22521. BABYLON.serialize()
  22522. ], Camera.prototype, "inertia", void 0);
  22523. __decorate([
  22524. BABYLON.serialize()
  22525. ], Camera.prototype, "mode", void 0);
  22526. __decorate([
  22527. BABYLON.serialize()
  22528. ], Camera.prototype, "layerMask", void 0);
  22529. __decorate([
  22530. BABYLON.serialize()
  22531. ], Camera.prototype, "fovMode", void 0);
  22532. __decorate([
  22533. BABYLON.serialize()
  22534. ], Camera.prototype, "cameraRigMode", void 0);
  22535. __decorate([
  22536. BABYLON.serialize()
  22537. ], Camera.prototype, "interaxialDistance", void 0);
  22538. __decorate([
  22539. BABYLON.serialize()
  22540. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22541. return Camera;
  22542. }(BABYLON.Node));
  22543. BABYLON.Camera = Camera;
  22544. })(BABYLON || (BABYLON = {}));
  22545. //# sourceMappingURL=babylon.camera.js.map
  22546. var BABYLON;
  22547. (function (BABYLON) {
  22548. var RenderingManager = /** @class */ (function () {
  22549. function RenderingManager(scene) {
  22550. this._renderingGroups = new Array();
  22551. this._autoClearDepthStencil = {};
  22552. this._customOpaqueSortCompareFn = {};
  22553. this._customAlphaTestSortCompareFn = {};
  22554. this._customTransparentSortCompareFn = {};
  22555. this._renderinGroupInfo = null;
  22556. this._scene = scene;
  22557. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22558. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22559. }
  22560. }
  22561. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22562. if (depth === void 0) { depth = true; }
  22563. if (stencil === void 0) { stencil = true; }
  22564. if (this._depthStencilBufferAlreadyCleaned) {
  22565. return;
  22566. }
  22567. this._scene.getEngine().clear(null, false, depth, stencil);
  22568. this._depthStencilBufferAlreadyCleaned = true;
  22569. };
  22570. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22571. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22572. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22573. var info = null;
  22574. if (observable) {
  22575. if (!this._renderinGroupInfo) {
  22576. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22577. }
  22578. info = this._renderinGroupInfo;
  22579. info.scene = this._scene;
  22580. info.camera = this._scene.activeCamera;
  22581. }
  22582. // Dispatch sprites
  22583. if (renderSprites) {
  22584. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22585. var manager = this._scene.spriteManagers[index];
  22586. this.dispatchSprites(manager);
  22587. }
  22588. }
  22589. // Render
  22590. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22591. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22592. var renderingGroup = this._renderingGroups[index];
  22593. if (!renderingGroup && !observable)
  22594. continue;
  22595. var renderingGroupMask = 0;
  22596. // Fire PRECLEAR stage
  22597. if (observable && info) {
  22598. renderingGroupMask = Math.pow(2, index);
  22599. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22600. info.renderingGroupId = index;
  22601. observable.notifyObservers(info, renderingGroupMask);
  22602. }
  22603. // Clear depth/stencil if needed
  22604. if (RenderingManager.AUTOCLEAR) {
  22605. var autoClear = this._autoClearDepthStencil[index];
  22606. if (autoClear && autoClear.autoClear) {
  22607. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22608. }
  22609. }
  22610. if (observable && info) {
  22611. // Fire PREOPAQUE stage
  22612. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22613. observable.notifyObservers(info, renderingGroupMask);
  22614. // Fire PRETRANSPARENT stage
  22615. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22616. observable.notifyObservers(info, renderingGroupMask);
  22617. }
  22618. if (renderingGroup)
  22619. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22620. // Fire POSTTRANSPARENT stage
  22621. if (observable && info) {
  22622. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22623. observable.notifyObservers(info, renderingGroupMask);
  22624. }
  22625. }
  22626. };
  22627. RenderingManager.prototype.reset = function () {
  22628. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22629. var renderingGroup = this._renderingGroups[index];
  22630. if (renderingGroup) {
  22631. renderingGroup.prepare();
  22632. }
  22633. }
  22634. };
  22635. RenderingManager.prototype.dispose = function () {
  22636. this.freeRenderingGroups();
  22637. this._renderingGroups.length = 0;
  22638. };
  22639. /**
  22640. * Clear the info related to rendering groups preventing retention points during dispose.
  22641. */
  22642. RenderingManager.prototype.freeRenderingGroups = function () {
  22643. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22644. var renderingGroup = this._renderingGroups[index];
  22645. if (renderingGroup) {
  22646. renderingGroup.dispose();
  22647. }
  22648. }
  22649. };
  22650. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22651. if (this._renderingGroups[renderingGroupId] === undefined) {
  22652. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22653. }
  22654. };
  22655. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22656. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22657. this._prepareRenderingGroup(renderingGroupId);
  22658. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22659. };
  22660. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22661. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22662. this._prepareRenderingGroup(renderingGroupId);
  22663. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22664. };
  22665. /**
  22666. * @param subMesh The submesh to dispatch
  22667. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22668. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22669. */
  22670. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22671. if (mesh === undefined) {
  22672. mesh = subMesh.getMesh();
  22673. }
  22674. var renderingGroupId = mesh.renderingGroupId || 0;
  22675. this._prepareRenderingGroup(renderingGroupId);
  22676. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22677. };
  22678. /**
  22679. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22680. * This allowed control for front to back rendering or reversly depending of the special needs.
  22681. *
  22682. * @param renderingGroupId The rendering group id corresponding to its index
  22683. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22684. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22685. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22686. */
  22687. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22688. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22689. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22690. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22691. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22692. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22693. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22694. if (this._renderingGroups[renderingGroupId]) {
  22695. var group = this._renderingGroups[renderingGroupId];
  22696. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22697. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22698. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22699. }
  22700. };
  22701. /**
  22702. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22703. *
  22704. * @param renderingGroupId The rendering group id corresponding to its index
  22705. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22706. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22707. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22708. */
  22709. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22710. if (depth === void 0) { depth = true; }
  22711. if (stencil === void 0) { stencil = true; }
  22712. this._autoClearDepthStencil[renderingGroupId] = {
  22713. autoClear: autoClearDepthStencil,
  22714. depth: depth,
  22715. stencil: stencil
  22716. };
  22717. };
  22718. /**
  22719. * The max id used for rendering groups (not included)
  22720. */
  22721. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22722. /**
  22723. * The min id used for rendering groups (included)
  22724. */
  22725. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22726. /**
  22727. * Used to globally prevent autoclearing scenes.
  22728. */
  22729. RenderingManager.AUTOCLEAR = true;
  22730. return RenderingManager;
  22731. }());
  22732. BABYLON.RenderingManager = RenderingManager;
  22733. })(BABYLON || (BABYLON = {}));
  22734. //# sourceMappingURL=babylon.renderingManager.js.map
  22735. var BABYLON;
  22736. (function (BABYLON) {
  22737. var RenderingGroup = /** @class */ (function () {
  22738. /**
  22739. * Creates a new rendering group.
  22740. * @param index The rendering group index
  22741. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22742. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22743. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22744. */
  22745. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22746. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22747. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22748. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22749. this.index = index;
  22750. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22751. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22752. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22753. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22754. this._particleSystems = new BABYLON.SmartArray(256);
  22755. this._spriteManagers = new BABYLON.SmartArray(256);
  22756. this._edgesRenderers = new BABYLON.SmartArray(16);
  22757. this._scene = scene;
  22758. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22759. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22760. this.transparentSortCompareFn = transparentSortCompareFn;
  22761. }
  22762. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22763. /**
  22764. * Set the opaque sort comparison function.
  22765. * If null the sub meshes will be render in the order they were created
  22766. */
  22767. set: function (value) {
  22768. this._opaqueSortCompareFn = value;
  22769. if (value) {
  22770. this._renderOpaque = this.renderOpaqueSorted;
  22771. }
  22772. else {
  22773. this._renderOpaque = RenderingGroup.renderUnsorted;
  22774. }
  22775. },
  22776. enumerable: true,
  22777. configurable: true
  22778. });
  22779. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22780. /**
  22781. * Set the alpha test sort comparison function.
  22782. * If null the sub meshes will be render in the order they were created
  22783. */
  22784. set: function (value) {
  22785. this._alphaTestSortCompareFn = value;
  22786. if (value) {
  22787. this._renderAlphaTest = this.renderAlphaTestSorted;
  22788. }
  22789. else {
  22790. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22791. }
  22792. },
  22793. enumerable: true,
  22794. configurable: true
  22795. });
  22796. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22797. /**
  22798. * Set the transparent sort comparison function.
  22799. * If null the sub meshes will be render in the order they were created
  22800. */
  22801. set: function (value) {
  22802. if (value) {
  22803. this._transparentSortCompareFn = value;
  22804. }
  22805. else {
  22806. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22807. }
  22808. this._renderTransparent = this.renderTransparentSorted;
  22809. },
  22810. enumerable: true,
  22811. configurable: true
  22812. });
  22813. /**
  22814. * Render all the sub meshes contained in the group.
  22815. * @param customRenderFunction Used to override the default render behaviour of the group.
  22816. * @returns true if rendered some submeshes.
  22817. */
  22818. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22819. if (customRenderFunction) {
  22820. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22821. return;
  22822. }
  22823. var engine = this._scene.getEngine();
  22824. // Depth only
  22825. if (this._depthOnlySubMeshes.length !== 0) {
  22826. engine.setColorWrite(false);
  22827. this._renderAlphaTest(this._depthOnlySubMeshes);
  22828. engine.setColorWrite(true);
  22829. }
  22830. // Opaque
  22831. if (this._opaqueSubMeshes.length !== 0) {
  22832. this._renderOpaque(this._opaqueSubMeshes);
  22833. }
  22834. // Alpha test
  22835. if (this._alphaTestSubMeshes.length !== 0) {
  22836. this._renderAlphaTest(this._alphaTestSubMeshes);
  22837. }
  22838. var stencilState = engine.getStencilBuffer();
  22839. engine.setStencilBuffer(false);
  22840. // Sprites
  22841. if (renderSprites) {
  22842. this._renderSprites();
  22843. }
  22844. // Particles
  22845. if (renderParticles) {
  22846. this._renderParticles(activeMeshes);
  22847. }
  22848. if (this.onBeforeTransparentRendering) {
  22849. this.onBeforeTransparentRendering();
  22850. }
  22851. // Transparent
  22852. if (this._transparentSubMeshes.length !== 0) {
  22853. this._renderTransparent(this._transparentSubMeshes);
  22854. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22855. }
  22856. // Set back stencil to false in case it changes before the edge renderer.
  22857. engine.setStencilBuffer(false);
  22858. // Edges
  22859. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22860. this._edgesRenderers.data[edgesRendererIndex].render();
  22861. }
  22862. // Restore Stencil state.
  22863. engine.setStencilBuffer(stencilState);
  22864. };
  22865. /**
  22866. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22867. * @param subMeshes The submeshes to render
  22868. */
  22869. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22870. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22871. };
  22872. /**
  22873. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22874. * @param subMeshes The submeshes to render
  22875. */
  22876. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22877. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22878. };
  22879. /**
  22880. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22881. * @param subMeshes The submeshes to render
  22882. */
  22883. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22884. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22885. };
  22886. /**
  22887. * Renders the submeshes in a specified order.
  22888. * @param subMeshes The submeshes to sort before render
  22889. * @param sortCompareFn The comparison function use to sort
  22890. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22891. * @param transparent Specifies to activate blending if true
  22892. */
  22893. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22894. var subIndex = 0;
  22895. var subMesh;
  22896. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22897. for (; subIndex < subMeshes.length; subIndex++) {
  22898. subMesh = subMeshes.data[subIndex];
  22899. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22900. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22901. }
  22902. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22903. if (sortCompareFn) {
  22904. sortedArray.sort(sortCompareFn);
  22905. }
  22906. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22907. subMesh = sortedArray[subIndex];
  22908. if (transparent) {
  22909. var material = subMesh.getMaterial();
  22910. if (material && material.needDepthPrePass) {
  22911. var engine = material.getScene().getEngine();
  22912. engine.setColorWrite(false);
  22913. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22914. subMesh.render(false);
  22915. engine.setColorWrite(true);
  22916. }
  22917. }
  22918. subMesh.render(transparent);
  22919. }
  22920. };
  22921. /**
  22922. * Renders the submeshes in the order they were dispatched (no sort applied).
  22923. * @param subMeshes The submeshes to render
  22924. */
  22925. RenderingGroup.renderUnsorted = function (subMeshes) {
  22926. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22927. var submesh = subMeshes.data[subIndex];
  22928. submesh.render(false);
  22929. }
  22930. };
  22931. /**
  22932. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22933. * are rendered back to front if in the same alpha index.
  22934. *
  22935. * @param a The first submesh
  22936. * @param b The second submesh
  22937. * @returns The result of the comparison
  22938. */
  22939. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22940. // Alpha index first
  22941. if (a._alphaIndex > b._alphaIndex) {
  22942. return 1;
  22943. }
  22944. if (a._alphaIndex < b._alphaIndex) {
  22945. return -1;
  22946. }
  22947. // Then distance to camera
  22948. return RenderingGroup.backToFrontSortCompare(a, b);
  22949. };
  22950. /**
  22951. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22952. * are rendered back to front.
  22953. *
  22954. * @param a The first submesh
  22955. * @param b The second submesh
  22956. * @returns The result of the comparison
  22957. */
  22958. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22959. // Then distance to camera
  22960. if (a._distanceToCamera < b._distanceToCamera) {
  22961. return 1;
  22962. }
  22963. if (a._distanceToCamera > b._distanceToCamera) {
  22964. return -1;
  22965. }
  22966. return 0;
  22967. };
  22968. /**
  22969. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22970. * are rendered front to back (prevent overdraw).
  22971. *
  22972. * @param a The first submesh
  22973. * @param b The second submesh
  22974. * @returns The result of the comparison
  22975. */
  22976. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22977. // Then distance to camera
  22978. if (a._distanceToCamera < b._distanceToCamera) {
  22979. return -1;
  22980. }
  22981. if (a._distanceToCamera > b._distanceToCamera) {
  22982. return 1;
  22983. }
  22984. return 0;
  22985. };
  22986. /**
  22987. * Resets the different lists of submeshes to prepare a new frame.
  22988. */
  22989. RenderingGroup.prototype.prepare = function () {
  22990. this._opaqueSubMeshes.reset();
  22991. this._transparentSubMeshes.reset();
  22992. this._alphaTestSubMeshes.reset();
  22993. this._depthOnlySubMeshes.reset();
  22994. this._particleSystems.reset();
  22995. this._spriteManagers.reset();
  22996. this._edgesRenderers.reset();
  22997. };
  22998. RenderingGroup.prototype.dispose = function () {
  22999. this._opaqueSubMeshes.dispose();
  23000. this._transparentSubMeshes.dispose();
  23001. this._alphaTestSubMeshes.dispose();
  23002. this._depthOnlySubMeshes.dispose();
  23003. this._particleSystems.dispose();
  23004. this._spriteManagers.dispose();
  23005. this._edgesRenderers.dispose();
  23006. };
  23007. /**
  23008. * Inserts the submesh in its correct queue depending on its material.
  23009. * @param subMesh The submesh to dispatch
  23010. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23011. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23012. */
  23013. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23014. // Get mesh and materials if not provided
  23015. if (mesh === undefined) {
  23016. mesh = subMesh.getMesh();
  23017. }
  23018. if (material === undefined) {
  23019. material = subMesh.getMaterial();
  23020. }
  23021. if (material === null || material === undefined) {
  23022. return;
  23023. }
  23024. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23025. this._transparentSubMeshes.push(subMesh);
  23026. }
  23027. else if (material.needAlphaTesting()) { // Alpha test
  23028. if (material.needDepthPrePass) {
  23029. this._depthOnlySubMeshes.push(subMesh);
  23030. }
  23031. this._alphaTestSubMeshes.push(subMesh);
  23032. }
  23033. else {
  23034. if (material.needDepthPrePass) {
  23035. this._depthOnlySubMeshes.push(subMesh);
  23036. }
  23037. this._opaqueSubMeshes.push(subMesh); // Opaque
  23038. }
  23039. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23040. this._edgesRenderers.push(mesh._edgesRenderer);
  23041. }
  23042. };
  23043. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23044. this._spriteManagers.push(spriteManager);
  23045. };
  23046. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23047. this._particleSystems.push(particleSystem);
  23048. };
  23049. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23050. if (this._particleSystems.length === 0) {
  23051. return;
  23052. }
  23053. // Particles
  23054. var activeCamera = this._scene.activeCamera;
  23055. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23056. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23057. var particleSystem = this._particleSystems.data[particleIndex];
  23058. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23059. continue;
  23060. }
  23061. var emitter = particleSystem.emitter;
  23062. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23063. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23064. }
  23065. }
  23066. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23067. };
  23068. RenderingGroup.prototype._renderSprites = function () {
  23069. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23070. return;
  23071. }
  23072. // Sprites
  23073. var activeCamera = this._scene.activeCamera;
  23074. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23075. for (var id = 0; id < this._spriteManagers.length; id++) {
  23076. var spriteManager = this._spriteManagers.data[id];
  23077. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23078. spriteManager.render();
  23079. }
  23080. }
  23081. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23082. };
  23083. return RenderingGroup;
  23084. }());
  23085. BABYLON.RenderingGroup = RenderingGroup;
  23086. })(BABYLON || (BABYLON = {}));
  23087. //# sourceMappingURL=babylon.renderingGroup.js.map
  23088. var BABYLON;
  23089. (function (BABYLON) {
  23090. /** @ignore */
  23091. var ClickInfo = /** @class */ (function () {
  23092. function ClickInfo() {
  23093. this._singleClick = false;
  23094. this._doubleClick = false;
  23095. this._hasSwiped = false;
  23096. this._ignore = false;
  23097. }
  23098. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23099. get: function () {
  23100. return this._singleClick;
  23101. },
  23102. set: function (b) {
  23103. this._singleClick = b;
  23104. },
  23105. enumerable: true,
  23106. configurable: true
  23107. });
  23108. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23109. get: function () {
  23110. return this._doubleClick;
  23111. },
  23112. set: function (b) {
  23113. this._doubleClick = b;
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23119. get: function () {
  23120. return this._hasSwiped;
  23121. },
  23122. set: function (b) {
  23123. this._hasSwiped = b;
  23124. },
  23125. enumerable: true,
  23126. configurable: true
  23127. });
  23128. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23129. get: function () {
  23130. return this._ignore;
  23131. },
  23132. set: function (b) {
  23133. this._ignore = b;
  23134. },
  23135. enumerable: true,
  23136. configurable: true
  23137. });
  23138. return ClickInfo;
  23139. }());
  23140. /**
  23141. * This class is used by the onRenderingGroupObservable
  23142. */
  23143. var RenderingGroupInfo = /** @class */ (function () {
  23144. function RenderingGroupInfo() {
  23145. }
  23146. /**
  23147. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23148. * This stage will be fired no matter what
  23149. */
  23150. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23151. /**
  23152. * Called before opaque object are rendered.
  23153. * This stage will be fired only if there's 3D Opaque content to render
  23154. */
  23155. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23156. /**
  23157. * Called after the opaque objects are rendered and before the transparent ones
  23158. * This stage will be fired only if there's 3D transparent content to render
  23159. */
  23160. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23161. /**
  23162. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23163. * This stage will be fired no matter what
  23164. */
  23165. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23166. return RenderingGroupInfo;
  23167. }());
  23168. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23169. /**
  23170. * Represents a scene to be rendered by the engine.
  23171. * @see http://doc.babylonjs.com/features/scene
  23172. */
  23173. var Scene = /** @class */ (function () {
  23174. /**
  23175. * Creates a new Scene
  23176. * @param engine defines the engine to use to render this scene
  23177. */
  23178. function Scene(engine) {
  23179. // Members
  23180. /**
  23181. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23182. */
  23183. this.autoClear = true;
  23184. /**
  23185. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23186. */
  23187. this.autoClearDepthAndStencil = true;
  23188. /**
  23189. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23190. */
  23191. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23192. /**
  23193. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23194. */
  23195. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23196. this._forceWireframe = false;
  23197. this._forcePointsCloud = false;
  23198. /**
  23199. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23200. */
  23201. this.forceShowBoundingBoxes = false;
  23202. /**
  23203. * Gets or sets a boolean indicating if animations are enabled
  23204. */
  23205. this.animationsEnabled = true;
  23206. this._animationPropertiesOverride = null;
  23207. /**
  23208. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23209. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23210. */
  23211. this.useConstantAnimationDeltaTime = false;
  23212. /**
  23213. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23214. * Please note that it requires to run a ray cast through the scene on every frame
  23215. */
  23216. this.constantlyUpdateMeshUnderPointer = false;
  23217. /**
  23218. * Defines the HTML cursor to use when hovering over interactive elements
  23219. */
  23220. this.hoverCursor = "pointer";
  23221. /**
  23222. * Defines the HTML default cursor to use (empty by default)
  23223. */
  23224. this.defaultCursor = "";
  23225. /**
  23226. * This is used to call preventDefault() on pointer down
  23227. * in order to block unwanted artifacts like system double clicks
  23228. */
  23229. this.preventDefaultOnPointerDown = true;
  23230. // Metadata
  23231. /**
  23232. * Gets or sets user defined metadata
  23233. */
  23234. this.metadata = null;
  23235. /**
  23236. * Use this array to add regular expressions used to disable offline support for specific urls
  23237. */
  23238. this.disableOfflineSupportExceptionRules = new Array();
  23239. /**
  23240. * An event triggered when the scene is disposed.
  23241. */
  23242. this.onDisposeObservable = new BABYLON.Observable();
  23243. this._onDisposeObserver = null;
  23244. /**
  23245. * An event triggered before rendering the scene (right after animations and physics)
  23246. */
  23247. this.onBeforeRenderObservable = new BABYLON.Observable();
  23248. this._onBeforeRenderObserver = null;
  23249. /**
  23250. * An event triggered after rendering the scene
  23251. */
  23252. this.onAfterRenderObservable = new BABYLON.Observable();
  23253. this._onAfterRenderObserver = null;
  23254. /**
  23255. * An event triggered before animating the scene
  23256. */
  23257. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23258. /**
  23259. * An event triggered after animations processing
  23260. */
  23261. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23262. /**
  23263. * An event triggered before draw calls are ready to be sent
  23264. */
  23265. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23266. /**
  23267. * An event triggered after draw calls have been sent
  23268. */
  23269. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23270. /**
  23271. * An event triggered when physic simulation is about to be run
  23272. */
  23273. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23274. /**
  23275. * An event triggered when physic simulation has been done
  23276. */
  23277. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23278. /**
  23279. * An event triggered when the scene is ready
  23280. */
  23281. this.onReadyObservable = new BABYLON.Observable();
  23282. /**
  23283. * An event triggered before rendering a camera
  23284. */
  23285. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23286. this._onBeforeCameraRenderObserver = null;
  23287. /**
  23288. * An event triggered after rendering a camera
  23289. */
  23290. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23291. this._onAfterCameraRenderObserver = null;
  23292. /**
  23293. * An event triggered when active meshes evaluation is about to start
  23294. */
  23295. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23296. /**
  23297. * An event triggered when active meshes evaluation is done
  23298. */
  23299. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23300. /**
  23301. * An event triggered when particles rendering is about to start
  23302. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23303. */
  23304. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23305. /**
  23306. * An event triggered when particles rendering is done
  23307. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23308. */
  23309. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23310. /**
  23311. * An event triggered when sprites rendering is about to start
  23312. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23313. */
  23314. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23315. /**
  23316. * An event triggered when sprites rendering is done
  23317. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23318. */
  23319. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23320. /**
  23321. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23322. */
  23323. this.onDataLoadedObservable = new BABYLON.Observable();
  23324. /**
  23325. * An event triggered when a camera is created
  23326. */
  23327. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23328. /**
  23329. * An event triggered when a camera is removed
  23330. */
  23331. this.onCameraRemovedObservable = new BABYLON.Observable();
  23332. /**
  23333. * An event triggered when a light is created
  23334. */
  23335. this.onNewLightAddedObservable = new BABYLON.Observable();
  23336. /**
  23337. * An event triggered when a light is removed
  23338. */
  23339. this.onLightRemovedObservable = new BABYLON.Observable();
  23340. /**
  23341. * An event triggered when a geometry is created
  23342. */
  23343. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23344. /**
  23345. * An event triggered when a geometry is removed
  23346. */
  23347. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23348. /**
  23349. * An event triggered when a transform node is created
  23350. */
  23351. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23352. /**
  23353. * An event triggered when a transform node is removed
  23354. */
  23355. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23356. /**
  23357. * An event triggered when a mesh is created
  23358. */
  23359. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23360. /**
  23361. * An event triggered when a mesh is removed
  23362. */
  23363. this.onMeshRemovedObservable = new BABYLON.Observable();
  23364. /**
  23365. * An event triggered when render targets are about to be rendered
  23366. * Can happen multiple times per frame.
  23367. */
  23368. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23369. /**
  23370. * An event triggered when render targets were rendered.
  23371. * Can happen multiple times per frame.
  23372. */
  23373. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23374. /**
  23375. * An event triggered before calculating deterministic simulation step
  23376. */
  23377. this.onBeforeStepObservable = new BABYLON.Observable();
  23378. /**
  23379. * An event triggered after calculating deterministic simulation step
  23380. */
  23381. this.onAfterStepObservable = new BABYLON.Observable();
  23382. /**
  23383. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23384. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23385. * 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)
  23386. */
  23387. this.onRenderingGroupObservable = new BABYLON.Observable();
  23388. // Animations
  23389. /**
  23390. * Gets a list of Animations associated with the scene
  23391. */
  23392. this.animations = [];
  23393. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23394. /**
  23395. * 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).
  23396. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23397. */
  23398. this.onPrePointerObservable = new BABYLON.Observable();
  23399. /**
  23400. * Observable event triggered each time an input event is received from the rendering canvas
  23401. */
  23402. this.onPointerObservable = new BABYLON.Observable();
  23403. this._meshPickProceed = false;
  23404. this._currentPickResult = null;
  23405. this._previousPickResult = null;
  23406. this._totalPointersPressed = 0;
  23407. this._doubleClickOccured = false;
  23408. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23409. this.cameraToUseForPointers = null;
  23410. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23411. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23412. this._startingPointerTime = 0;
  23413. this._previousStartingPointerTime = 0;
  23414. // Deterministic lockstep
  23415. this._timeAccumulator = 0;
  23416. this._currentStepId = 0;
  23417. this._currentInternalStep = 0;
  23418. // Keyboard
  23419. /**
  23420. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23421. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23422. */
  23423. this.onPreKeyboardObservable = new BABYLON.Observable();
  23424. /**
  23425. * Observable event triggered each time an keyboard event is received from the hosting window
  23426. */
  23427. this.onKeyboardObservable = new BABYLON.Observable();
  23428. // Coordinates system
  23429. this._useRightHandedSystem = false;
  23430. // Fog
  23431. this._fogEnabled = true;
  23432. this._fogMode = Scene.FOGMODE_NONE;
  23433. /**
  23434. * Gets or sets the fog color to use
  23435. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23436. */
  23437. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23438. /**
  23439. * Gets or sets the fog density to use
  23440. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23441. */
  23442. this.fogDensity = 0.1;
  23443. /**
  23444. * Gets or sets the fog start distance to use
  23445. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23446. */
  23447. this.fogStart = 0;
  23448. /**
  23449. * Gets or sets the fog end distance to use
  23450. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23451. */
  23452. this.fogEnd = 1000.0;
  23453. // Lights
  23454. this._shadowsEnabled = true;
  23455. this._lightsEnabled = true;
  23456. /**
  23457. * All of the lights added to this scene
  23458. * @see http://doc.babylonjs.com/babylon101/lights
  23459. */
  23460. this.lights = new Array();
  23461. // Cameras
  23462. /** All of the cameras added to this scene.
  23463. * @see http://doc.babylonjs.com/babylon101/cameras
  23464. */
  23465. this.cameras = new Array();
  23466. /** All of the active cameras added to this scene. */
  23467. this.activeCameras = new Array();
  23468. // Meshes
  23469. /**
  23470. * All of the tranform nodes added to this scene
  23471. * @see http://doc.babylonjs.com/how_to/transformnode
  23472. */
  23473. this.transformNodes = new Array();
  23474. /**
  23475. * All of the (abstract) meshes added to this scene
  23476. */
  23477. this.meshes = new Array();
  23478. /**
  23479. * All of the animation groups added to this scene
  23480. * @see http://doc.babylonjs.com/how_to/group
  23481. */
  23482. this.animationGroups = new Array();
  23483. // Geometries
  23484. this._geometries = new Array();
  23485. /**
  23486. * All of the materials added to this scene
  23487. * @see http://doc.babylonjs.com/babylon101/materials
  23488. */
  23489. this.materials = new Array();
  23490. /**
  23491. * All of the multi-materials added to this scene
  23492. * @see http://doc.babylonjs.com/how_to/multi_materials
  23493. */
  23494. this.multiMaterials = new Array();
  23495. // Textures
  23496. this._texturesEnabled = true;
  23497. /**
  23498. * All of the textures added to this scene
  23499. */
  23500. this.textures = new Array();
  23501. // Particles
  23502. /**
  23503. * Gets or sets a boolean indicating if particles are enabled on this scene
  23504. */
  23505. this.particlesEnabled = true;
  23506. /**
  23507. * All of the particle systems added to this scene
  23508. * @see http://doc.babylonjs.com/babylon101/particles
  23509. */
  23510. this.particleSystems = new Array();
  23511. // Sprites
  23512. /**
  23513. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23514. */
  23515. this.spritesEnabled = true;
  23516. /**
  23517. * All of the sprite managers added to this scene
  23518. * @see http://doc.babylonjs.com/babylon101/sprites
  23519. */
  23520. this.spriteManagers = new Array();
  23521. /**
  23522. * The list of layers (background and foreground) of the scene
  23523. */
  23524. this.layers = new Array();
  23525. /**
  23526. * The list of effect layers (highlights/glow) added to the scene
  23527. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23528. * @see http://doc.babylonjs.com/how_to/glow_layer
  23529. */
  23530. this.effectLayers = new Array();
  23531. // Skeletons
  23532. this._skeletonsEnabled = true;
  23533. /**
  23534. * The list of skeletons added to the scene
  23535. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23536. */
  23537. this.skeletons = new Array();
  23538. // Morph targets
  23539. /**
  23540. * The list of morph target managers added to the scene
  23541. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23542. */
  23543. this.morphTargetManagers = new Array();
  23544. // Lens flares
  23545. /**
  23546. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23547. */
  23548. this.lensFlaresEnabled = true;
  23549. /**
  23550. * The list of lens flare system added to the scene
  23551. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23552. */
  23553. this.lensFlareSystems = new Array();
  23554. // Collisions
  23555. /**
  23556. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23557. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23558. */
  23559. this.collisionsEnabled = true;
  23560. /**
  23561. * Defines the gravity applied to this scene (used only for collisions)
  23562. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23563. */
  23564. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23565. // Postprocesses
  23566. /**
  23567. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23568. */
  23569. this.postProcessesEnabled = true;
  23570. /**
  23571. * The list of postprocesses added to the scene
  23572. */
  23573. this.postProcesses = new Array();
  23574. // Customs render targets
  23575. /**
  23576. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23577. */
  23578. this.renderTargetsEnabled = true;
  23579. /**
  23580. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23581. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23582. */
  23583. this.dumpNextRenderTargets = false;
  23584. /**
  23585. * The list of user defined render targets added to the scene
  23586. */
  23587. this.customRenderTargets = new Array();
  23588. /**
  23589. * Gets the list of meshes imported to the scene through SceneLoader
  23590. */
  23591. this.importedMeshesFiles = new Array();
  23592. // Probes
  23593. /**
  23594. * Gets or sets a boolean indicating if probes are enabled on this scene
  23595. */
  23596. this.probesEnabled = true;
  23597. /**
  23598. * The list of reflection probes added to the scene
  23599. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23600. */
  23601. this.reflectionProbes = new Array();
  23602. /** @ignore */
  23603. this._actionManagers = new Array();
  23604. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23605. // Procedural textures
  23606. /**
  23607. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23608. */
  23609. this.proceduralTexturesEnabled = true;
  23610. /**
  23611. * The list of procedural textures added to the scene
  23612. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23613. */
  23614. this.proceduralTextures = new Array();
  23615. /**
  23616. * The list of sound tracks added to the scene
  23617. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23618. */
  23619. this.soundTracks = new Array();
  23620. this._audioEnabled = true;
  23621. this._headphone = false;
  23622. // Performance counters
  23623. this._totalVertices = new BABYLON.PerfCounter();
  23624. /** @ignore */
  23625. this._activeIndices = new BABYLON.PerfCounter();
  23626. /** @ignore */
  23627. this._activeParticles = new BABYLON.PerfCounter();
  23628. /** @ignore */
  23629. this._activeBones = new BABYLON.PerfCounter();
  23630. this._animationTime = 0;
  23631. /**
  23632. * Gets or sets a general scale for animation speed
  23633. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23634. */
  23635. this.animationTimeScale = 1;
  23636. this._renderId = 0;
  23637. this._executeWhenReadyTimeoutId = -1;
  23638. this._intermediateRendering = false;
  23639. this._viewUpdateFlag = -1;
  23640. this._projectionUpdateFlag = -1;
  23641. this._alternateViewUpdateFlag = -1;
  23642. this._alternateProjectionUpdateFlag = -1;
  23643. /** @ignore */
  23644. this._toBeDisposed = new BABYLON.SmartArray(256);
  23645. this._activeRequests = new Array();
  23646. this._pendingData = new Array();
  23647. this._isDisposed = false;
  23648. /**
  23649. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23650. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23651. */
  23652. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23653. this._activeMeshes = new BABYLON.SmartArray(256);
  23654. this._processedMaterials = new BABYLON.SmartArray(256);
  23655. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23656. /** @ignore */
  23657. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23658. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23659. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23660. /** @ignore */
  23661. this._activeAnimatables = new Array();
  23662. this._transformMatrix = BABYLON.Matrix.Zero();
  23663. this._useAlternateCameraConfiguration = false;
  23664. this._alternateRendering = false;
  23665. /**
  23666. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23667. * This is useful if there are more lights that the maximum simulteanous authorized
  23668. */
  23669. this.requireLightSorting = false;
  23670. this._depthRenderer = {};
  23671. this._activeMeshesFrozen = false;
  23672. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23673. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23674. this._engine.scenes.push(this);
  23675. this._uid = null;
  23676. this._renderingManager = new BABYLON.RenderingManager(this);
  23677. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23678. if (BABYLON.OutlineRenderer) {
  23679. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23680. }
  23681. if (BABYLON.Tools.IsWindowObjectExist()) {
  23682. this.attachControl();
  23683. }
  23684. //simplification queue
  23685. if (BABYLON.SimplificationQueue) {
  23686. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23687. }
  23688. //collision coordinator initialization. For now legacy per default.
  23689. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23690. // Uniform Buffer
  23691. this._createUbo();
  23692. // Default Image processing definition.
  23693. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23694. }
  23695. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23696. /** The fog is deactivated */
  23697. get: function () {
  23698. return Scene._FOGMODE_NONE;
  23699. },
  23700. enumerable: true,
  23701. configurable: true
  23702. });
  23703. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23704. /** The fog density is following an exponential function */
  23705. get: function () {
  23706. return Scene._FOGMODE_EXP;
  23707. },
  23708. enumerable: true,
  23709. configurable: true
  23710. });
  23711. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23712. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23713. get: function () {
  23714. return Scene._FOGMODE_EXP2;
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23720. /** The fog density is following a linear function. */
  23721. get: function () {
  23722. return Scene._FOGMODE_LINEAR;
  23723. },
  23724. enumerable: true,
  23725. configurable: true
  23726. });
  23727. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23728. /**
  23729. * Texture used in all pbr material as the reflection texture.
  23730. * As in the majority of the scene they are the same (exception for multi room and so on),
  23731. * this is easier to reference from here than from all the materials.
  23732. */
  23733. get: function () {
  23734. return this._environmentTexture;
  23735. },
  23736. /**
  23737. * Texture used in all pbr material as the reflection texture.
  23738. * As in the majority of the scene they are the same (exception for multi room and so on),
  23739. * this is easier to set here than in all the materials.
  23740. */
  23741. set: function (value) {
  23742. if (this._environmentTexture === value) {
  23743. return;
  23744. }
  23745. this._environmentTexture = value;
  23746. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23752. /**
  23753. * Default image processing configuration used either in the rendering
  23754. * Forward main pass or through the imageProcessingPostProcess if present.
  23755. * As in the majority of the scene they are the same (exception for multi camera),
  23756. * this is easier to reference from here than from all the materials and post process.
  23757. *
  23758. * No setter as we it is a shared configuration, you can set the values instead.
  23759. */
  23760. get: function () {
  23761. return this._imageProcessingConfiguration;
  23762. },
  23763. enumerable: true,
  23764. configurable: true
  23765. });
  23766. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23767. get: function () {
  23768. return this._forceWireframe;
  23769. },
  23770. /**
  23771. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23772. */
  23773. set: function (value) {
  23774. if (this._forceWireframe === value) {
  23775. return;
  23776. }
  23777. this._forceWireframe = value;
  23778. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23779. },
  23780. enumerable: true,
  23781. configurable: true
  23782. });
  23783. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23784. get: function () {
  23785. return this._forcePointsCloud;
  23786. },
  23787. /**
  23788. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23789. */
  23790. set: function (value) {
  23791. if (this._forcePointsCloud === value) {
  23792. return;
  23793. }
  23794. this._forcePointsCloud = value;
  23795. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23801. /**
  23802. * Gets or sets the animation properties override
  23803. */
  23804. get: function () {
  23805. return this._animationPropertiesOverride;
  23806. },
  23807. set: function (value) {
  23808. this._animationPropertiesOverride = value;
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Object.defineProperty(Scene.prototype, "onDispose", {
  23814. /** Sets a function to be executed when this scene is disposed. */
  23815. set: function (callback) {
  23816. if (this._onDisposeObserver) {
  23817. this.onDisposeObservable.remove(this._onDisposeObserver);
  23818. }
  23819. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23820. },
  23821. enumerable: true,
  23822. configurable: true
  23823. });
  23824. Object.defineProperty(Scene.prototype, "beforeRender", {
  23825. /** Sets a function to be executed before rendering this scene */
  23826. set: function (callback) {
  23827. if (this._onBeforeRenderObserver) {
  23828. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23829. }
  23830. if (callback) {
  23831. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23832. }
  23833. },
  23834. enumerable: true,
  23835. configurable: true
  23836. });
  23837. Object.defineProperty(Scene.prototype, "afterRender", {
  23838. /** Sets a function to be executed after rendering this scene */
  23839. set: function (callback) {
  23840. if (this._onAfterRenderObserver) {
  23841. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23842. }
  23843. if (callback) {
  23844. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23845. }
  23846. },
  23847. enumerable: true,
  23848. configurable: true
  23849. });
  23850. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23851. /** Sets a function to be executed before rendering a camera*/
  23852. set: function (callback) {
  23853. if (this._onBeforeCameraRenderObserver) {
  23854. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23855. }
  23856. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23862. /** Sets a function to be executed after rendering a camera*/
  23863. set: function (callback) {
  23864. if (this._onAfterCameraRenderObserver) {
  23865. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23866. }
  23867. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23868. },
  23869. enumerable: true,
  23870. configurable: true
  23871. });
  23872. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23873. /**
  23874. * Gets the gamepad manager associated with the scene
  23875. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23876. */
  23877. get: function () {
  23878. if (!this._gamepadManager) {
  23879. this._gamepadManager = new BABYLON.GamepadManager(this);
  23880. }
  23881. return this._gamepadManager;
  23882. },
  23883. enumerable: true,
  23884. configurable: true
  23885. });
  23886. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23887. /**
  23888. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23889. */
  23890. get: function () {
  23891. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23892. },
  23893. enumerable: true,
  23894. configurable: true
  23895. });
  23896. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23897. get: function () {
  23898. return this._useRightHandedSystem;
  23899. },
  23900. /**
  23901. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23902. */
  23903. set: function (value) {
  23904. if (this._useRightHandedSystem === value) {
  23905. return;
  23906. }
  23907. this._useRightHandedSystem = value;
  23908. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23909. },
  23910. enumerable: true,
  23911. configurable: true
  23912. });
  23913. /**
  23914. * Sets the step Id used by deterministic lock step
  23915. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23916. * @param newStepId defines the step Id
  23917. */
  23918. Scene.prototype.setStepId = function (newStepId) {
  23919. this._currentStepId = newStepId;
  23920. };
  23921. ;
  23922. /**
  23923. * Gets the step Id used by deterministic lock step
  23924. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23925. * @returns the step Id
  23926. */
  23927. Scene.prototype.getStepId = function () {
  23928. return this._currentStepId;
  23929. };
  23930. ;
  23931. /**
  23932. * Gets the internal step used by deterministic lock step
  23933. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23934. * @returns the internal step
  23935. */
  23936. Scene.prototype.getInternalStep = function () {
  23937. return this._currentInternalStep;
  23938. };
  23939. ;
  23940. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23941. get: function () {
  23942. return this._fogEnabled;
  23943. },
  23944. /**
  23945. * Gets or sets a boolean indicating if fog is enabled on this scene
  23946. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23947. */
  23948. set: function (value) {
  23949. if (this._fogEnabled === value) {
  23950. return;
  23951. }
  23952. this._fogEnabled = value;
  23953. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. Object.defineProperty(Scene.prototype, "fogMode", {
  23959. get: function () {
  23960. return this._fogMode;
  23961. },
  23962. /**
  23963. * Gets or sets the fog mode to use
  23964. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23965. */
  23966. set: function (value) {
  23967. if (this._fogMode === value) {
  23968. return;
  23969. }
  23970. this._fogMode = value;
  23971. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23977. get: function () {
  23978. return this._shadowsEnabled;
  23979. },
  23980. /**
  23981. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23982. */
  23983. set: function (value) {
  23984. if (this._shadowsEnabled === value) {
  23985. return;
  23986. }
  23987. this._shadowsEnabled = value;
  23988. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23989. },
  23990. enumerable: true,
  23991. configurable: true
  23992. });
  23993. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23994. get: function () {
  23995. return this._lightsEnabled;
  23996. },
  23997. /**
  23998. * Gets or sets a boolean indicating if lights are enabled on this scene
  23999. */
  24000. set: function (value) {
  24001. if (this._lightsEnabled === value) {
  24002. return;
  24003. }
  24004. this._lightsEnabled = value;
  24005. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24006. },
  24007. enumerable: true,
  24008. configurable: true
  24009. });
  24010. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24011. /** The default material used on meshes when no material is affected */
  24012. get: function () {
  24013. if (!this._defaultMaterial) {
  24014. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24015. }
  24016. return this._defaultMaterial;
  24017. },
  24018. /** The default material used on meshes when no material is affected */
  24019. set: function (value) {
  24020. this._defaultMaterial = value;
  24021. },
  24022. enumerable: true,
  24023. configurable: true
  24024. });
  24025. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24026. get: function () {
  24027. return this._texturesEnabled;
  24028. },
  24029. /**
  24030. * Gets or sets a boolean indicating if textures are enabled on this scene
  24031. */
  24032. set: function (value) {
  24033. if (this._texturesEnabled === value) {
  24034. return;
  24035. }
  24036. this._texturesEnabled = value;
  24037. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24038. },
  24039. enumerable: true,
  24040. configurable: true
  24041. });
  24042. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24043. get: function () {
  24044. return this._skeletonsEnabled;
  24045. },
  24046. /**
  24047. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24048. */
  24049. set: function (value) {
  24050. if (this._skeletonsEnabled === value) {
  24051. return;
  24052. }
  24053. this._skeletonsEnabled = value;
  24054. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24060. /**
  24061. * Gets the postprocess render pipeline manager
  24062. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24063. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24064. */
  24065. get: function () {
  24066. if (!this._postProcessRenderPipelineManager) {
  24067. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24068. }
  24069. return this._postProcessRenderPipelineManager;
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24075. /**
  24076. * Gets the main soundtrack associated with the scene
  24077. */
  24078. get: function () {
  24079. if (!this._mainSoundTrack) {
  24080. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24081. }
  24082. return this._mainSoundTrack;
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24088. /** @ignore */
  24089. get: function () {
  24090. return this._alternateRendering;
  24091. },
  24092. enumerable: true,
  24093. configurable: true
  24094. });
  24095. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24096. /**
  24097. * Gets the list of frustum planes (built from the active camera)
  24098. */
  24099. get: function () {
  24100. return this._frustumPlanes;
  24101. },
  24102. enumerable: true,
  24103. configurable: true
  24104. });
  24105. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24106. /**
  24107. * Gets the current geometry buffer associated to the scene.
  24108. */
  24109. get: function () {
  24110. return this._geometryBufferRenderer;
  24111. },
  24112. /**
  24113. * Sets the current geometry buffer for the scene.
  24114. */
  24115. set: function (geometryBufferRenderer) {
  24116. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24117. this._geometryBufferRenderer = geometryBufferRenderer;
  24118. }
  24119. },
  24120. enumerable: true,
  24121. configurable: true
  24122. });
  24123. Object.defineProperty(Scene.prototype, "debugLayer", {
  24124. /**
  24125. * Gets the debug layer associated with the scene
  24126. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24127. */
  24128. get: function () {
  24129. if (!this._debugLayer) {
  24130. this._debugLayer = new BABYLON.DebugLayer(this);
  24131. }
  24132. return this._debugLayer;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24138. /**
  24139. * Gets a boolean indicating if collisions are processed on a web worker
  24140. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24141. */
  24142. get: function () {
  24143. return this._workerCollisions;
  24144. },
  24145. set: function (enabled) {
  24146. if (!BABYLON.CollisionCoordinatorLegacy) {
  24147. return;
  24148. }
  24149. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24150. this._workerCollisions = enabled;
  24151. if (this.collisionCoordinator) {
  24152. this.collisionCoordinator.destroy();
  24153. }
  24154. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24155. this.collisionCoordinator.init(this);
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24161. /**
  24162. * Gets the octree used to boost mesh selection (picking)
  24163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24164. */
  24165. get: function () {
  24166. return this._selectionOctree;
  24167. },
  24168. enumerable: true,
  24169. configurable: true
  24170. });
  24171. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24172. /**
  24173. * Gets the mesh that is currently under the pointer
  24174. */
  24175. get: function () {
  24176. return this._pointerOverMesh;
  24177. },
  24178. enumerable: true,
  24179. configurable: true
  24180. });
  24181. Object.defineProperty(Scene.prototype, "pointerX", {
  24182. /**
  24183. * Gets the current on-screen X position of the pointer
  24184. */
  24185. get: function () {
  24186. return this._pointerX;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "pointerY", {
  24192. /**
  24193. * Gets the current on-screen Y position of the pointer
  24194. */
  24195. get: function () {
  24196. return this._pointerY;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. /**
  24202. * Gets the cached material (ie. the latest rendered one)
  24203. * @returns the cached material
  24204. */
  24205. Scene.prototype.getCachedMaterial = function () {
  24206. return this._cachedMaterial;
  24207. };
  24208. /**
  24209. * Gets the cached effect (ie. the latest rendered one)
  24210. * @returns the cached effect
  24211. */
  24212. Scene.prototype.getCachedEffect = function () {
  24213. return this._cachedEffect;
  24214. };
  24215. /**
  24216. * Gets the cached visibility state (ie. the latest rendered one)
  24217. * @returns the cached visibility state
  24218. */
  24219. Scene.prototype.getCachedVisibility = function () {
  24220. return this._cachedVisibility;
  24221. };
  24222. /**
  24223. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24224. * @param material defines the current material
  24225. * @param effect defines the current effect
  24226. * @param visibility defines the current visibility state
  24227. * @returns true if one parameter is not cached
  24228. */
  24229. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24230. if (visibility === void 0) { visibility = 1; }
  24231. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24232. };
  24233. /**
  24234. * Gets the bounding box renderer associated with the scene
  24235. * @returns a BoundingBoxRenderer
  24236. */
  24237. Scene.prototype.getBoundingBoxRenderer = function () {
  24238. if (!this._boundingBoxRenderer) {
  24239. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24240. }
  24241. return this._boundingBoxRenderer;
  24242. };
  24243. /**
  24244. * Gets the outline renderer associated with the scene
  24245. * @returns a OutlineRenderer
  24246. */
  24247. Scene.prototype.getOutlineRenderer = function () {
  24248. return this._outlineRenderer;
  24249. };
  24250. /**
  24251. * Gets the engine associated with the scene
  24252. * @returns an Engine
  24253. */
  24254. Scene.prototype.getEngine = function () {
  24255. return this._engine;
  24256. };
  24257. /**
  24258. * Gets the total number of vertices rendered per frame
  24259. * @returns the total number of vertices rendered per frame
  24260. */
  24261. Scene.prototype.getTotalVertices = function () {
  24262. return this._totalVertices.current;
  24263. };
  24264. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24265. /**
  24266. * Gets the performance counter for total vertices
  24267. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24268. */
  24269. get: function () {
  24270. return this._totalVertices;
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. /**
  24276. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24277. * @returns the total number of active indices rendered per frame
  24278. */
  24279. Scene.prototype.getActiveIndices = function () {
  24280. return this._activeIndices.current;
  24281. };
  24282. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24283. /**
  24284. * Gets the performance counter for active indices
  24285. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24286. */
  24287. get: function () {
  24288. return this._activeIndices;
  24289. },
  24290. enumerable: true,
  24291. configurable: true
  24292. });
  24293. /**
  24294. * Gets the total number of active particles rendered per frame
  24295. * @returns the total number of active particles rendered per frame
  24296. */
  24297. Scene.prototype.getActiveParticles = function () {
  24298. return this._activeParticles.current;
  24299. };
  24300. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24301. /**
  24302. * Gets the performance counter for active particles
  24303. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24304. */
  24305. get: function () {
  24306. return this._activeParticles;
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. /**
  24312. * Gets the total number of active bones rendered per frame
  24313. * @returns the total number of active bones rendered per frame
  24314. */
  24315. Scene.prototype.getActiveBones = function () {
  24316. return this._activeBones.current;
  24317. };
  24318. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24319. /**
  24320. * Gets the performance counter for active bones
  24321. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24322. */
  24323. get: function () {
  24324. return this._activeBones;
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. /** @ignore */
  24330. Scene.prototype.getInterFramePerfCounter = function () {
  24331. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24332. return 0;
  24333. };
  24334. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24335. /** @ignore */
  24336. get: function () {
  24337. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24338. return null;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. /** @ignore */
  24344. Scene.prototype.getLastFrameDuration = function () {
  24345. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24346. return 0;
  24347. };
  24348. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24349. /** @ignore */
  24350. get: function () {
  24351. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24352. return null;
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. /** @ignore */
  24358. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24359. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24360. return 0;
  24361. };
  24362. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24363. /** @ignore */
  24364. get: function () {
  24365. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24366. return null;
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. /**
  24372. * Gets the array of active meshes
  24373. * @returns an array of AbstractMesh
  24374. */
  24375. Scene.prototype.getActiveMeshes = function () {
  24376. return this._activeMeshes;
  24377. };
  24378. /** @ignore */
  24379. Scene.prototype.getRenderTargetsDuration = function () {
  24380. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24381. return 0;
  24382. };
  24383. /** @ignore */
  24384. Scene.prototype.getRenderDuration = function () {
  24385. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24386. return 0;
  24387. };
  24388. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24389. /** @ignore */
  24390. get: function () {
  24391. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24392. return null;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. /** @ignore */
  24398. Scene.prototype.getParticlesDuration = function () {
  24399. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24400. return 0;
  24401. };
  24402. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24403. /** @ignore */
  24404. get: function () {
  24405. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24406. return null;
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. /** @ignore */
  24412. Scene.prototype.getSpritesDuration = function () {
  24413. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24414. return 0;
  24415. };
  24416. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24417. /** @ignore */
  24418. get: function () {
  24419. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24420. return null;
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. /**
  24426. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24427. * @returns a number
  24428. */
  24429. Scene.prototype.getAnimationRatio = function () {
  24430. return this._animationRatio;
  24431. };
  24432. /**
  24433. * Gets an unique Id for the current frame
  24434. * @returns a number
  24435. */
  24436. Scene.prototype.getRenderId = function () {
  24437. return this._renderId;
  24438. };
  24439. /** Call this function if you want to manually increment the render Id*/
  24440. Scene.prototype.incrementRenderId = function () {
  24441. this._renderId++;
  24442. };
  24443. Scene.prototype._updatePointerPosition = function (evt) {
  24444. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24445. if (!canvasRect) {
  24446. return;
  24447. }
  24448. this._pointerX = evt.clientX - canvasRect.left;
  24449. this._pointerY = evt.clientY - canvasRect.top;
  24450. this._unTranslatedPointerX = this._pointerX;
  24451. this._unTranslatedPointerY = this._pointerY;
  24452. };
  24453. Scene.prototype._createUbo = function () {
  24454. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24455. this._sceneUbo.addUniform("viewProjection", 16);
  24456. this._sceneUbo.addUniform("view", 16);
  24457. };
  24458. Scene.prototype._createAlternateUbo = function () {
  24459. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24460. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24461. this._alternateSceneUbo.addUniform("view", 16);
  24462. };
  24463. // Pointers handling
  24464. /**
  24465. * Use this method to simulate a pointer move on a mesh
  24466. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24467. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24468. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24469. * @returns the current scene
  24470. */
  24471. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24472. var evt = new PointerEvent("pointermove", pointerEventInit);
  24473. return this._processPointerMove(pickResult, evt);
  24474. };
  24475. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24476. var canvas = this._engine.getRenderingCanvas();
  24477. if (!canvas) {
  24478. return this;
  24479. }
  24480. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24481. this.setPointerOverSprite(null);
  24482. this.setPointerOverMesh(pickResult.pickedMesh);
  24483. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24484. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24485. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24486. }
  24487. else {
  24488. canvas.style.cursor = this.hoverCursor;
  24489. }
  24490. }
  24491. else {
  24492. canvas.style.cursor = this.defaultCursor;
  24493. }
  24494. }
  24495. else {
  24496. this.setPointerOverMesh(null);
  24497. // Sprites
  24498. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24499. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24500. this.setPointerOverSprite(pickResult.pickedSprite);
  24501. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24502. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24503. }
  24504. else {
  24505. canvas.style.cursor = this.hoverCursor;
  24506. }
  24507. }
  24508. else {
  24509. this.setPointerOverSprite(null);
  24510. // Restore pointer
  24511. canvas.style.cursor = this.defaultCursor;
  24512. }
  24513. }
  24514. if (pickResult) {
  24515. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24516. if (this.onPointerMove) {
  24517. this.onPointerMove(evt, pickResult, type);
  24518. }
  24519. if (this.onPointerObservable.hasObservers()) {
  24520. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24521. this.onPointerObservable.notifyObservers(pi, type);
  24522. }
  24523. }
  24524. return this;
  24525. };
  24526. /**
  24527. * Use this method to simulate a pointer down on a mesh
  24528. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24529. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24530. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24531. * @returns the current scene
  24532. */
  24533. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24534. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24535. return this._processPointerDown(pickResult, evt);
  24536. };
  24537. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24538. var _this = this;
  24539. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24540. this._pickedDownMesh = pickResult.pickedMesh;
  24541. var actionManager = pickResult.pickedMesh.actionManager;
  24542. if (actionManager) {
  24543. if (actionManager.hasPickTriggers) {
  24544. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24545. switch (evt.button) {
  24546. case 0:
  24547. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24548. break;
  24549. case 1:
  24550. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24551. break;
  24552. case 2:
  24553. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24554. break;
  24555. }
  24556. }
  24557. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24558. window.setTimeout(function () {
  24559. 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);
  24560. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24561. if (_this._totalPointersPressed !== 0 &&
  24562. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24563. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24564. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24565. _this._startingPointerTime = 0;
  24566. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24567. }
  24568. }
  24569. }, Scene.LongPressDelay);
  24570. }
  24571. }
  24572. }
  24573. if (pickResult) {
  24574. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24575. if (this.onPointerDown) {
  24576. this.onPointerDown(evt, pickResult, type);
  24577. }
  24578. if (this.onPointerObservable.hasObservers()) {
  24579. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24580. this.onPointerObservable.notifyObservers(pi, type);
  24581. }
  24582. }
  24583. return this;
  24584. };
  24585. /**
  24586. * Use this method to simulate a pointer up on a mesh
  24587. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24588. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24589. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24590. * @returns the current scene
  24591. */
  24592. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24593. var evt = new PointerEvent("pointerup", pointerEventInit);
  24594. var clickInfo = new ClickInfo();
  24595. clickInfo.singleClick = true;
  24596. clickInfo.ignore = true;
  24597. return this._processPointerUp(pickResult, evt, clickInfo);
  24598. };
  24599. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24600. if (pickResult && pickResult && pickResult.pickedMesh) {
  24601. this._pickedUpMesh = pickResult.pickedMesh;
  24602. if (this._pickedDownMesh === this._pickedUpMesh) {
  24603. if (this.onPointerPick) {
  24604. this.onPointerPick(evt, pickResult);
  24605. }
  24606. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24607. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24608. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24609. this.onPointerObservable.notifyObservers(pi, type_1);
  24610. }
  24611. }
  24612. if (pickResult.pickedMesh.actionManager) {
  24613. if (clickInfo.ignore) {
  24614. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24615. }
  24616. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24617. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24618. }
  24619. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24620. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24621. }
  24622. }
  24623. }
  24624. if (this._pickedDownMesh &&
  24625. this._pickedDownMesh.actionManager &&
  24626. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24627. this._pickedDownMesh !== this._pickedUpMesh) {
  24628. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24629. }
  24630. var type = BABYLON.PointerEventTypes.POINTERUP;
  24631. if (this.onPointerObservable.hasObservers()) {
  24632. if (!clickInfo.ignore) {
  24633. if (!clickInfo.hasSwiped) {
  24634. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24635. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24636. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24637. this.onPointerObservable.notifyObservers(pi, type_2);
  24638. }
  24639. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24640. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24641. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24642. this.onPointerObservable.notifyObservers(pi, type_3);
  24643. }
  24644. }
  24645. }
  24646. else {
  24647. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24648. this.onPointerObservable.notifyObservers(pi, type);
  24649. }
  24650. }
  24651. if (this.onPointerUp) {
  24652. this.onPointerUp(evt, pickResult, type);
  24653. }
  24654. return this;
  24655. };
  24656. /**
  24657. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24658. * @param attachUp defines if you want to attach events to pointerup
  24659. * @param attachDown defines if you want to attach events to pointerdown
  24660. * @param attachMove defines if you want to attach events to pointermove
  24661. */
  24662. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24663. var _this = this;
  24664. if (attachUp === void 0) { attachUp = true; }
  24665. if (attachDown === void 0) { attachDown = true; }
  24666. if (attachMove === void 0) { attachMove = true; }
  24667. this._initActionManager = function (act, clickInfo) {
  24668. if (!_this._meshPickProceed) {
  24669. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24670. _this._currentPickResult = pickResult;
  24671. if (pickResult) {
  24672. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24673. }
  24674. _this._meshPickProceed = true;
  24675. }
  24676. return act;
  24677. };
  24678. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24679. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24680. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24681. btn !== _this._previousButtonPressed) {
  24682. _this._doubleClickOccured = false;
  24683. clickInfo.singleClick = true;
  24684. clickInfo.ignore = false;
  24685. cb(clickInfo, _this._currentPickResult);
  24686. }
  24687. };
  24688. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24689. var clickInfo = new ClickInfo();
  24690. _this._currentPickResult = null;
  24691. var act = null;
  24692. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24693. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24694. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24695. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24696. act = _this._initActionManager(act, clickInfo);
  24697. if (act)
  24698. checkPicking = act.hasPickTriggers;
  24699. }
  24700. if (checkPicking) {
  24701. var btn = evt.button;
  24702. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24703. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24704. if (!clickInfo.hasSwiped) {
  24705. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24706. if (!checkSingleClickImmediately) {
  24707. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24708. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24709. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24710. act = _this._initActionManager(act, clickInfo);
  24711. if (act)
  24712. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24713. }
  24714. }
  24715. if (checkSingleClickImmediately) {
  24716. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24717. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24718. btn !== _this._previousButtonPressed) {
  24719. clickInfo.singleClick = true;
  24720. cb(clickInfo, _this._currentPickResult);
  24721. }
  24722. }
  24723. // at least one double click is required to be check and exclusive double click is enabled
  24724. else {
  24725. // wait that no double click has been raised during the double click delay
  24726. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24727. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24728. }
  24729. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24730. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24731. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24732. act = _this._initActionManager(act, clickInfo);
  24733. if (act)
  24734. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24735. }
  24736. if (checkDoubleClick) {
  24737. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24738. if (btn === _this._previousButtonPressed &&
  24739. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24740. !_this._doubleClickOccured) {
  24741. // pointer has not moved for 2 clicks, it's a double click
  24742. if (!clickInfo.hasSwiped &&
  24743. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24744. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24745. _this._previousStartingPointerTime = 0;
  24746. _this._doubleClickOccured = true;
  24747. clickInfo.doubleClick = true;
  24748. clickInfo.ignore = false;
  24749. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24750. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24751. }
  24752. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24753. cb(clickInfo, _this._currentPickResult);
  24754. }
  24755. // if the two successive clicks are too far, it's just two simple clicks
  24756. else {
  24757. _this._doubleClickOccured = false;
  24758. _this._previousStartingPointerTime = _this._startingPointerTime;
  24759. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24760. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24761. _this._previousButtonPressed = btn;
  24762. if (Scene.ExclusiveDoubleClickMode) {
  24763. if (_this._previousDelayedSimpleClickTimeout) {
  24764. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24765. }
  24766. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24767. cb(clickInfo, _this._previousPickResult);
  24768. }
  24769. else {
  24770. cb(clickInfo, _this._currentPickResult);
  24771. }
  24772. }
  24773. }
  24774. // just the first click of the double has been raised
  24775. else {
  24776. _this._doubleClickOccured = false;
  24777. _this._previousStartingPointerTime = _this._startingPointerTime;
  24778. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24779. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24780. _this._previousButtonPressed = btn;
  24781. }
  24782. }
  24783. }
  24784. }
  24785. clickInfo.ignore = true;
  24786. cb(clickInfo, _this._currentPickResult);
  24787. };
  24788. this._spritePredicate = function (sprite) {
  24789. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24790. };
  24791. this._onPointerMove = function (evt) {
  24792. _this._updatePointerPosition(evt);
  24793. // PreObservable support
  24794. if (_this.onPrePointerObservable.hasObservers()) {
  24795. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24796. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24797. _this.onPrePointerObservable.notifyObservers(pi, type);
  24798. if (pi.skipOnPointerObservable) {
  24799. return;
  24800. }
  24801. }
  24802. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24803. return;
  24804. }
  24805. if (!_this.pointerMovePredicate) {
  24806. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24807. }
  24808. // Meshes
  24809. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24810. _this._processPointerMove(pickResult, evt);
  24811. };
  24812. this._onPointerDown = function (evt) {
  24813. _this._totalPointersPressed++;
  24814. _this._pickedDownMesh = null;
  24815. _this._meshPickProceed = false;
  24816. _this._updatePointerPosition(evt);
  24817. if (_this.preventDefaultOnPointerDown && canvas) {
  24818. evt.preventDefault();
  24819. canvas.focus();
  24820. }
  24821. // PreObservable support
  24822. if (_this.onPrePointerObservable.hasObservers()) {
  24823. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24824. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24825. _this.onPrePointerObservable.notifyObservers(pi, type);
  24826. if (pi.skipOnPointerObservable) {
  24827. return;
  24828. }
  24829. }
  24830. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24831. return;
  24832. }
  24833. _this._startingPointerPosition.x = _this._pointerX;
  24834. _this._startingPointerPosition.y = _this._pointerY;
  24835. _this._startingPointerTime = Date.now();
  24836. if (!_this.pointerDownPredicate) {
  24837. _this.pointerDownPredicate = function (mesh) {
  24838. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24839. };
  24840. }
  24841. // Meshes
  24842. _this._pickedDownMesh = null;
  24843. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24844. _this._processPointerDown(pickResult, evt);
  24845. // Sprites
  24846. _this._pickedDownSprite = null;
  24847. if (_this.spriteManagers.length > 0) {
  24848. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24849. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24850. if (pickResult.pickedSprite.actionManager) {
  24851. _this._pickedDownSprite = pickResult.pickedSprite;
  24852. switch (evt.button) {
  24853. case 0:
  24854. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24855. break;
  24856. case 1:
  24857. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24858. break;
  24859. case 2:
  24860. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24861. break;
  24862. }
  24863. if (pickResult.pickedSprite.actionManager) {
  24864. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24865. }
  24866. }
  24867. }
  24868. }
  24869. };
  24870. this._onPointerUp = function (evt) {
  24871. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  24872. return; // So we need to test it the pointer down was pressed before.
  24873. }
  24874. _this._totalPointersPressed--;
  24875. _this._pickedUpMesh = null;
  24876. _this._meshPickProceed = false;
  24877. _this._updatePointerPosition(evt);
  24878. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24879. // PreObservable support
  24880. if (_this.onPrePointerObservable.hasObservers()) {
  24881. if (!clickInfo.ignore) {
  24882. if (!clickInfo.hasSwiped) {
  24883. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24884. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24885. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24886. _this.onPrePointerObservable.notifyObservers(pi, type);
  24887. if (pi.skipOnPointerObservable) {
  24888. return;
  24889. }
  24890. }
  24891. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24892. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24893. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24894. _this.onPrePointerObservable.notifyObservers(pi, type);
  24895. if (pi.skipOnPointerObservable) {
  24896. return;
  24897. }
  24898. }
  24899. }
  24900. }
  24901. else {
  24902. var type = BABYLON.PointerEventTypes.POINTERUP;
  24903. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24904. _this.onPrePointerObservable.notifyObservers(pi, type);
  24905. if (pi.skipOnPointerObservable) {
  24906. return;
  24907. }
  24908. }
  24909. }
  24910. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24911. return;
  24912. }
  24913. if (!_this.pointerUpPredicate) {
  24914. _this.pointerUpPredicate = function (mesh) {
  24915. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24916. };
  24917. }
  24918. // Meshes
  24919. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24920. _this._initActionManager(null, clickInfo);
  24921. }
  24922. if (!pickResult) {
  24923. pickResult = _this._currentPickResult;
  24924. }
  24925. _this._processPointerUp(pickResult, evt, clickInfo);
  24926. // Sprites
  24927. if (_this.spriteManagers.length > 0) {
  24928. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24929. if (spritePickResult) {
  24930. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24931. if (spritePickResult.pickedSprite.actionManager) {
  24932. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24933. if (spritePickResult.pickedSprite.actionManager) {
  24934. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24935. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24936. }
  24937. }
  24938. }
  24939. }
  24940. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24941. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24942. }
  24943. }
  24944. }
  24945. _this._previousPickResult = _this._currentPickResult;
  24946. });
  24947. };
  24948. this._onKeyDown = function (evt) {
  24949. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24950. if (_this.onPreKeyboardObservable.hasObservers()) {
  24951. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24952. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24953. if (pi.skipOnPointerObservable) {
  24954. return;
  24955. }
  24956. }
  24957. if (_this.onKeyboardObservable.hasObservers()) {
  24958. var pi = new BABYLON.KeyboardInfo(type, evt);
  24959. _this.onKeyboardObservable.notifyObservers(pi, type);
  24960. }
  24961. if (_this.actionManager) {
  24962. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24963. }
  24964. };
  24965. this._onKeyUp = function (evt) {
  24966. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24967. if (_this.onPreKeyboardObservable.hasObservers()) {
  24968. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24969. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24970. if (pi.skipOnPointerObservable) {
  24971. return;
  24972. }
  24973. }
  24974. if (_this.onKeyboardObservable.hasObservers()) {
  24975. var pi = new BABYLON.KeyboardInfo(type, evt);
  24976. _this.onKeyboardObservable.notifyObservers(pi, type);
  24977. }
  24978. if (_this.actionManager) {
  24979. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24980. }
  24981. };
  24982. var engine = this.getEngine();
  24983. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24984. if (!canvas) {
  24985. return;
  24986. }
  24987. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24988. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24989. });
  24990. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24991. if (!canvas) {
  24992. return;
  24993. }
  24994. canvas.removeEventListener("keydown", _this._onKeyDown);
  24995. canvas.removeEventListener("keyup", _this._onKeyUp);
  24996. });
  24997. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24998. var canvas = this._engine.getRenderingCanvas();
  24999. if (!canvas) {
  25000. return;
  25001. }
  25002. if (attachMove) {
  25003. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25004. // Wheel
  25005. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25006. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25007. }
  25008. if (attachDown) {
  25009. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25010. }
  25011. if (attachUp) {
  25012. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25013. }
  25014. canvas.tabIndex = 1;
  25015. };
  25016. /** Detaches all event handlers*/
  25017. Scene.prototype.detachControl = function () {
  25018. var engine = this.getEngine();
  25019. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25020. var canvas = engine.getRenderingCanvas();
  25021. if (!canvas) {
  25022. return;
  25023. }
  25024. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25025. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25026. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25027. if (this._onCanvasBlurObserver) {
  25028. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25029. }
  25030. if (this._onCanvasFocusObserver) {
  25031. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25032. }
  25033. // Wheel
  25034. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25035. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25036. // Keyboard
  25037. canvas.removeEventListener("keydown", this._onKeyDown);
  25038. canvas.removeEventListener("keyup", this._onKeyUp);
  25039. // Observables
  25040. this.onKeyboardObservable.clear();
  25041. this.onPreKeyboardObservable.clear();
  25042. this.onPointerObservable.clear();
  25043. this.onPrePointerObservable.clear();
  25044. };
  25045. /**
  25046. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25047. * Delay loaded resources are not taking in account
  25048. * @return true if all required resources are ready
  25049. */
  25050. Scene.prototype.isReady = function () {
  25051. if (this._isDisposed) {
  25052. return false;
  25053. }
  25054. if (this._pendingData.length > 0) {
  25055. return false;
  25056. }
  25057. var index;
  25058. var engine = this.getEngine();
  25059. // Geometries
  25060. for (index = 0; index < this._geometries.length; index++) {
  25061. var geometry = this._geometries[index];
  25062. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25063. return false;
  25064. }
  25065. }
  25066. // Meshes
  25067. for (index = 0; index < this.meshes.length; index++) {
  25068. var mesh = this.meshes[index];
  25069. if (!mesh.isEnabled()) {
  25070. continue;
  25071. }
  25072. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25073. continue;
  25074. }
  25075. if (!mesh.isReady(true)) {
  25076. return false;
  25077. }
  25078. // Effect layers
  25079. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25080. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25081. var layer = _a[_i];
  25082. if (!layer.hasMesh(mesh)) {
  25083. continue;
  25084. }
  25085. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25086. var subMesh = _c[_b];
  25087. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25088. return false;
  25089. }
  25090. }
  25091. }
  25092. }
  25093. // Post-processes
  25094. if (this.activeCameras && this.activeCameras.length > 0) {
  25095. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25096. var camera = _e[_d];
  25097. if (!camera.isReady(true)) {
  25098. return false;
  25099. }
  25100. }
  25101. }
  25102. else if (this.activeCamera) {
  25103. if (!this.activeCamera.isReady(true)) {
  25104. return false;
  25105. }
  25106. }
  25107. // Particles
  25108. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25109. var particleSystem = _g[_f];
  25110. if (!particleSystem.isReady()) {
  25111. return false;
  25112. }
  25113. }
  25114. return true;
  25115. };
  25116. /** Resets all cached information relative to material (including effect and visibility) */
  25117. Scene.prototype.resetCachedMaterial = function () {
  25118. this._cachedMaterial = null;
  25119. this._cachedEffect = null;
  25120. this._cachedVisibility = null;
  25121. };
  25122. /**
  25123. * Registers a function to be called before every frame render
  25124. * @param func defines the function to register
  25125. */
  25126. Scene.prototype.registerBeforeRender = function (func) {
  25127. this.onBeforeRenderObservable.add(func);
  25128. };
  25129. /**
  25130. * Unregisters a function called before every frame render
  25131. * @param func defines the function to unregister
  25132. */
  25133. Scene.prototype.unregisterBeforeRender = function (func) {
  25134. this.onBeforeRenderObservable.removeCallback(func);
  25135. };
  25136. /**
  25137. * Registers a function to be called after every frame render
  25138. * @param func defines the function to register
  25139. */
  25140. Scene.prototype.registerAfterRender = function (func) {
  25141. this.onAfterRenderObservable.add(func);
  25142. };
  25143. /**
  25144. * Unregisters a function called after every frame render
  25145. * @param func defines the function to unregister
  25146. */
  25147. Scene.prototype.unregisterAfterRender = function (func) {
  25148. this.onAfterRenderObservable.removeCallback(func);
  25149. };
  25150. Scene.prototype._executeOnceBeforeRender = function (func) {
  25151. var _this = this;
  25152. var execFunc = function () {
  25153. func();
  25154. setTimeout(function () {
  25155. _this.unregisterBeforeRender(execFunc);
  25156. });
  25157. };
  25158. this.registerBeforeRender(execFunc);
  25159. };
  25160. /**
  25161. * The provided function will run before render once and will be disposed afterwards.
  25162. * A timeout delay can be provided so that the function will be executed in N ms.
  25163. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25164. * @param func The function to be executed.
  25165. * @param timeout optional delay in ms
  25166. */
  25167. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25168. var _this = this;
  25169. if (timeout !== undefined) {
  25170. setTimeout(function () {
  25171. _this._executeOnceBeforeRender(func);
  25172. }, timeout);
  25173. }
  25174. else {
  25175. this._executeOnceBeforeRender(func);
  25176. }
  25177. };
  25178. /** @ignore */
  25179. Scene.prototype._addPendingData = function (data) {
  25180. this._pendingData.push(data);
  25181. };
  25182. /** @ignore */
  25183. Scene.prototype._removePendingData = function (data) {
  25184. var wasLoading = this.isLoading;
  25185. var index = this._pendingData.indexOf(data);
  25186. if (index !== -1) {
  25187. this._pendingData.splice(index, 1);
  25188. }
  25189. if (wasLoading && !this.isLoading) {
  25190. this.onDataLoadedObservable.notifyObservers(this);
  25191. }
  25192. };
  25193. /**
  25194. * Returns the number of items waiting to be loaded
  25195. * @returns the number of items waiting to be loaded
  25196. */
  25197. Scene.prototype.getWaitingItemsCount = function () {
  25198. return this._pendingData.length;
  25199. };
  25200. Object.defineProperty(Scene.prototype, "isLoading", {
  25201. /**
  25202. * Returns a boolean indicating if the scene is still loading data
  25203. */
  25204. get: function () {
  25205. return this._pendingData.length > 0;
  25206. },
  25207. enumerable: true,
  25208. configurable: true
  25209. });
  25210. /**
  25211. * Registers a function to be executed when the scene is ready
  25212. * @param {Function} func - the function to be executed
  25213. */
  25214. Scene.prototype.executeWhenReady = function (func) {
  25215. var _this = this;
  25216. this.onReadyObservable.add(func);
  25217. if (this._executeWhenReadyTimeoutId !== -1) {
  25218. return;
  25219. }
  25220. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25221. _this._checkIsReady();
  25222. }, 150);
  25223. };
  25224. /**
  25225. * Returns a promise that resolves when the scene is ready
  25226. * @returns A promise that resolves when the scene is ready
  25227. */
  25228. Scene.prototype.whenReadyAsync = function () {
  25229. var _this = this;
  25230. return new Promise(function (resolve) {
  25231. _this.executeWhenReady(function () {
  25232. resolve();
  25233. });
  25234. });
  25235. };
  25236. /** @ignore */
  25237. Scene.prototype._checkIsReady = function () {
  25238. var _this = this;
  25239. if (this.isReady()) {
  25240. this.onReadyObservable.notifyObservers(this);
  25241. this.onReadyObservable.clear();
  25242. this._executeWhenReadyTimeoutId = -1;
  25243. return;
  25244. }
  25245. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25246. _this._checkIsReady();
  25247. }, 150);
  25248. };
  25249. // Animations
  25250. /**
  25251. * Will start the animation sequence of a given target
  25252. * @param target defines the target
  25253. * @param from defines from which frame should animation start
  25254. * @param to defines until which frame should animation run.
  25255. * @param weight defines the weight to apply to the animation (1.0 by default)
  25256. * @param loop defines if the animation loops
  25257. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25258. * @param onAnimationEnd defines the function to be executed when the animation ends
  25259. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25260. * @returns the animatable object created for this animation
  25261. */
  25262. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25263. if (weight === void 0) { weight = 1.0; }
  25264. if (speedRatio === void 0) { speedRatio = 1.0; }
  25265. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25266. returnedAnimatable.weight = weight;
  25267. return returnedAnimatable;
  25268. };
  25269. /**
  25270. * Will start the animation sequence of a given target
  25271. * @param target defines the target
  25272. * @param from defines from which frame should animation start
  25273. * @param to defines until which frame should animation run.
  25274. * @param loop defines if the animation loops
  25275. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25276. * @param onAnimationEnd defines the function to be executed when the animation ends
  25277. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25278. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25279. * @returns the animatable object created for this animation
  25280. */
  25281. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25282. if (speedRatio === void 0) { speedRatio = 1.0; }
  25283. if (stopCurrent === void 0) { stopCurrent = true; }
  25284. if (from > to && speedRatio > 0) {
  25285. speedRatio *= -1;
  25286. }
  25287. if (stopCurrent) {
  25288. this.stopAnimation(target);
  25289. }
  25290. if (!animatable) {
  25291. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25292. }
  25293. // Local animations
  25294. if (target.animations) {
  25295. animatable.appendAnimations(target, target.animations);
  25296. }
  25297. // Children animations
  25298. if (target.getAnimatables) {
  25299. var animatables = target.getAnimatables();
  25300. for (var index = 0; index < animatables.length; index++) {
  25301. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25302. }
  25303. }
  25304. animatable.reset();
  25305. return animatable;
  25306. };
  25307. /**
  25308. * Begin a new animation on a given node
  25309. * @param target defines the target where the animation will take place
  25310. * @param animations defines the list of animations to start
  25311. * @param from defines the initial value
  25312. * @param to defines the final value
  25313. * @param loop defines if you want animation to loop (off by default)
  25314. * @param speedRatio defines the speed ratio to apply to all animations
  25315. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25316. * @returns the list of created animatables
  25317. */
  25318. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25319. if (speedRatio === undefined) {
  25320. speedRatio = 1.0;
  25321. }
  25322. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25323. return animatable;
  25324. };
  25325. /**
  25326. * Begin a new animation on a given node and its hierarchy
  25327. * @param target defines the root node where the animation will take place
  25328. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25329. * @param animations defines the list of animations to start
  25330. * @param from defines the initial value
  25331. * @param to defines the final value
  25332. * @param loop defines if you want animation to loop (off by default)
  25333. * @param speedRatio defines the speed ratio to apply to all animations
  25334. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25335. * @returns the list of animatables created for all nodes
  25336. */
  25337. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25338. var children = target.getDescendants(directDescendantsOnly);
  25339. var result = [];
  25340. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25341. var child = children_1[_i];
  25342. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25343. }
  25344. return result;
  25345. };
  25346. /**
  25347. * Gets the animatable associated with a specific target
  25348. * @param target defines the target of the animatable
  25349. * @returns the required animatable if found
  25350. */
  25351. Scene.prototype.getAnimatableByTarget = function (target) {
  25352. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25353. if (this._activeAnimatables[index].target === target) {
  25354. return this._activeAnimatables[index];
  25355. }
  25356. }
  25357. return null;
  25358. };
  25359. /**
  25360. * Gets all animatables associated with a given target
  25361. * @param target defines the target to look animatables for
  25362. * @returns an array of Animatables
  25363. */
  25364. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25365. var result = [];
  25366. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25367. if (this._activeAnimatables[index].target === target) {
  25368. result.push(this._activeAnimatables[index]);
  25369. }
  25370. }
  25371. return result;
  25372. };
  25373. Object.defineProperty(Scene.prototype, "animatables", {
  25374. /**
  25375. * Gets all animatable attached to the scene
  25376. */
  25377. get: function () {
  25378. return this._activeAnimatables;
  25379. },
  25380. enumerable: true,
  25381. configurable: true
  25382. });
  25383. /**
  25384. * Will stop the animation of the given target
  25385. * @param target - the target
  25386. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25387. */
  25388. Scene.prototype.stopAnimation = function (target, animationName) {
  25389. var animatables = this.getAllAnimatablesByTarget(target);
  25390. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25391. var animatable = animatables_1[_i];
  25392. animatable.stop(animationName);
  25393. }
  25394. };
  25395. /**
  25396. * Stops and removes all animations that have been applied to the scene
  25397. */
  25398. Scene.prototype.stopAllAnimations = function () {
  25399. if (this._activeAnimatables) {
  25400. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25401. this._activeAnimatables[i].stop();
  25402. }
  25403. this._activeAnimatables = [];
  25404. }
  25405. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25406. var group = _a[_i];
  25407. group.stop();
  25408. }
  25409. };
  25410. Scene.prototype._animate = function () {
  25411. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25412. return;
  25413. }
  25414. // Getting time
  25415. var now = BABYLON.Tools.Now;
  25416. if (!this._animationTimeLast) {
  25417. if (this._pendingData.length > 0) {
  25418. return;
  25419. }
  25420. this._animationTimeLast = now;
  25421. }
  25422. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25423. this._animationTime += deltaTime;
  25424. this._animationTimeLast = now;
  25425. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25426. this._activeAnimatables[index]._animate(this._animationTime);
  25427. }
  25428. // Late animation bindings
  25429. this._processLateAnimationBindings();
  25430. };
  25431. /** @ignore */
  25432. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25433. var target = runtimeAnimation.target;
  25434. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25435. if (!target._lateAnimationHolders) {
  25436. target._lateAnimationHolders = {};
  25437. }
  25438. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25439. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25440. totalWeight: 0,
  25441. animations: []
  25442. };
  25443. }
  25444. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25445. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25446. };
  25447. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25448. var normalizer = 1.0;
  25449. var finalPosition = BABYLON.Tmp.Vector3[0];
  25450. var finalScaling = BABYLON.Tmp.Vector3[1];
  25451. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25452. var startIndex = 0;
  25453. var originalAnimation = holder.animations[0];
  25454. var scale = 1;
  25455. if (holder.totalWeight < 1.0) {
  25456. // We need to mix the original value in
  25457. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25458. scale = 1.0 - holder.totalWeight;
  25459. }
  25460. else {
  25461. startIndex = 1;
  25462. // We need to normalize the weights
  25463. normalizer = holder.totalWeight;
  25464. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25465. scale = originalAnimation.weight / normalizer;
  25466. if (scale == 1) {
  25467. return originalAnimation.currentValue;
  25468. }
  25469. }
  25470. finalScaling.scaleInPlace(scale);
  25471. finalPosition.scaleInPlace(scale);
  25472. finalQuaternion.scaleInPlace(scale);
  25473. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25474. var runtimeAnimation = holder.animations[animIndex];
  25475. var scale = runtimeAnimation.weight / normalizer;
  25476. var currentPosition = BABYLON.Tmp.Vector3[2];
  25477. var currentScaling = BABYLON.Tmp.Vector3[3];
  25478. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25479. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25480. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25481. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25482. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25483. }
  25484. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25485. return originalAnimation._workValue;
  25486. };
  25487. Scene.prototype._processLateAnimationBindings = function () {
  25488. if (!this._registeredForLateAnimationBindings.length) {
  25489. return;
  25490. }
  25491. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25492. var target = this._registeredForLateAnimationBindings.data[index];
  25493. for (var path in target._lateAnimationHolders) {
  25494. var holder = target._lateAnimationHolders[path];
  25495. var originalAnimation = holder.animations[0];
  25496. var originalValue = originalAnimation.originalValue;
  25497. var finalTarget = originalAnimation.target;
  25498. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25499. var finalValue = void 0;
  25500. if (matrixDecomposeMode) {
  25501. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25502. }
  25503. else {
  25504. var startIndex = 0;
  25505. var normalizer = 1.0;
  25506. if (holder.totalWeight < 1.0) {
  25507. // We need to mix the original value in
  25508. if (originalValue.scale) {
  25509. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25510. }
  25511. else {
  25512. finalValue = originalValue * (1.0 - holder.totalWeight);
  25513. }
  25514. }
  25515. else {
  25516. // We need to normalize the weights
  25517. normalizer = holder.totalWeight;
  25518. var scale_1 = originalAnimation.weight / normalizer;
  25519. if (scale_1 !== 1) {
  25520. if (originalAnimation.currentValue.scale) {
  25521. finalValue = originalAnimation.currentValue.scale(scale_1);
  25522. }
  25523. else {
  25524. finalValue = originalAnimation.currentValue * scale_1;
  25525. }
  25526. }
  25527. else {
  25528. finalValue = originalAnimation.currentValue;
  25529. }
  25530. startIndex = 1;
  25531. }
  25532. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25533. var runtimeAnimation = holder.animations[animIndex];
  25534. var scale = runtimeAnimation.weight / normalizer;
  25535. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25536. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25537. }
  25538. else {
  25539. finalValue += runtimeAnimation.currentValue * scale;
  25540. }
  25541. }
  25542. }
  25543. finalTarget[path] = finalValue;
  25544. }
  25545. target._lateAnimationHolders = {};
  25546. }
  25547. this._registeredForLateAnimationBindings.reset();
  25548. };
  25549. // Matrix
  25550. /** @ignore */
  25551. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25552. this._useAlternateCameraConfiguration = active;
  25553. };
  25554. /**
  25555. * Gets the current view matrix
  25556. * @returns a Matrix
  25557. */
  25558. Scene.prototype.getViewMatrix = function () {
  25559. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25560. };
  25561. /**
  25562. * Gets the current projection matrix
  25563. * @returns a Matrix
  25564. */
  25565. Scene.prototype.getProjectionMatrix = function () {
  25566. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25567. };
  25568. /**
  25569. * Gets the current transform matrix
  25570. * @returns a Matrix made of View * Projection
  25571. */
  25572. Scene.prototype.getTransformMatrix = function () {
  25573. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25574. };
  25575. /**
  25576. * Sets the current transform matrix
  25577. * @param view defines the View matrix to use
  25578. * @param projection defines the Projection matrix to use
  25579. */
  25580. Scene.prototype.setTransformMatrix = function (view, projection) {
  25581. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25582. return;
  25583. }
  25584. this._viewUpdateFlag = view.updateFlag;
  25585. this._projectionUpdateFlag = projection.updateFlag;
  25586. this._viewMatrix = view;
  25587. this._projectionMatrix = projection;
  25588. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25589. // Update frustum
  25590. if (!this._frustumPlanes) {
  25591. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25592. }
  25593. else {
  25594. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25595. }
  25596. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25597. var otherCamera = this.activeCamera._alternateCamera;
  25598. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25599. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25600. }
  25601. if (this._sceneUbo.useUbo) {
  25602. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25603. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25604. this._sceneUbo.update();
  25605. }
  25606. };
  25607. /** @ignore */
  25608. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25609. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25610. return;
  25611. }
  25612. this._alternateViewUpdateFlag = view.updateFlag;
  25613. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25614. this._alternateViewMatrix = view;
  25615. this._alternateProjectionMatrix = projection;
  25616. if (!this._alternateTransformMatrix) {
  25617. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25618. }
  25619. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25620. if (!this._alternateSceneUbo) {
  25621. this._createAlternateUbo();
  25622. }
  25623. if (this._alternateSceneUbo.useUbo) {
  25624. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25625. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25626. this._alternateSceneUbo.update();
  25627. }
  25628. };
  25629. /**
  25630. * Gets the uniform buffer used to store scene data
  25631. * @returns a UniformBuffer
  25632. */
  25633. Scene.prototype.getSceneUniformBuffer = function () {
  25634. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25635. };
  25636. /**
  25637. * Gets an unique (relatively to the current scene) Id
  25638. * @returns an unique number for the scene
  25639. */
  25640. Scene.prototype.getUniqueId = function () {
  25641. var result = Scene._uniqueIdCounter;
  25642. Scene._uniqueIdCounter++;
  25643. return result;
  25644. };
  25645. /**
  25646. * Add a mesh to the list of scene's meshes
  25647. * @param newMesh defines the mesh to add
  25648. */
  25649. Scene.prototype.addMesh = function (newMesh) {
  25650. this.meshes.push(newMesh);
  25651. //notify the collision coordinator
  25652. if (this.collisionCoordinator) {
  25653. this.collisionCoordinator.onMeshAdded(newMesh);
  25654. }
  25655. newMesh._resyncLightSources();
  25656. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25657. };
  25658. /**
  25659. * Remove a mesh for the list of scene's meshes
  25660. * @param toRemove defines the mesh to remove
  25661. * @returns the index where the mesh was in the mesh list
  25662. */
  25663. Scene.prototype.removeMesh = function (toRemove) {
  25664. var index = this.meshes.indexOf(toRemove);
  25665. if (index !== -1) {
  25666. // Remove from the scene if mesh found
  25667. this.meshes.splice(index, 1);
  25668. }
  25669. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25670. return index;
  25671. };
  25672. /**
  25673. * Add a transform node to the list of scene's transform nodes
  25674. * @param newTransformNode defines the transform node to add
  25675. */
  25676. Scene.prototype.addTransformNode = function (newTransformNode) {
  25677. this.transformNodes.push(newTransformNode);
  25678. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25679. };
  25680. /**
  25681. * Remove a transform node for the list of scene's transform nodes
  25682. * @param toRemove defines the transform node to remove
  25683. * @returns the index where the transform node was in the transform node list
  25684. */
  25685. Scene.prototype.removeTransformNode = function (toRemove) {
  25686. var index = this.transformNodes.indexOf(toRemove);
  25687. if (index !== -1) {
  25688. // Remove from the scene if found
  25689. this.transformNodes.splice(index, 1);
  25690. }
  25691. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25692. return index;
  25693. };
  25694. /**
  25695. * Remove a skeleton for the list of scene's skeletons
  25696. * @param toRemove defines the skeleton to remove
  25697. * @returns the index where the skeleton was in the skeleton list
  25698. */
  25699. Scene.prototype.removeSkeleton = function (toRemove) {
  25700. var index = this.skeletons.indexOf(toRemove);
  25701. if (index !== -1) {
  25702. // Remove from the scene if found
  25703. this.skeletons.splice(index, 1);
  25704. }
  25705. return index;
  25706. };
  25707. /**
  25708. * Remove a morph target for the list of scene's morph targets
  25709. * @param toRemove defines the morph target to remove
  25710. * @returns the index where the morph target was in the morph target list
  25711. */
  25712. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25713. var index = this.morphTargetManagers.indexOf(toRemove);
  25714. if (index !== -1) {
  25715. // Remove from the scene if found
  25716. this.morphTargetManagers.splice(index, 1);
  25717. }
  25718. return index;
  25719. };
  25720. /**
  25721. * Remove a light for the list of scene's lights
  25722. * @param toRemove defines the light to remove
  25723. * @returns the index where the light was in the light list
  25724. */
  25725. Scene.prototype.removeLight = function (toRemove) {
  25726. var index = this.lights.indexOf(toRemove);
  25727. if (index !== -1) {
  25728. // Remove from meshes
  25729. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25730. var mesh = _a[_i];
  25731. mesh._removeLightSource(toRemove);
  25732. }
  25733. // Remove from the scene if mesh found
  25734. this.lights.splice(index, 1);
  25735. this.sortLightsByPriority();
  25736. }
  25737. this.onLightRemovedObservable.notifyObservers(toRemove);
  25738. return index;
  25739. };
  25740. /**
  25741. * Remove a camera for the list of scene's cameras
  25742. * @param toRemove defines the camera to remove
  25743. * @returns the index where the camera was in the camera list
  25744. */
  25745. Scene.prototype.removeCamera = function (toRemove) {
  25746. var index = this.cameras.indexOf(toRemove);
  25747. if (index !== -1) {
  25748. // Remove from the scene if mesh found
  25749. this.cameras.splice(index, 1);
  25750. }
  25751. // Remove from activeCameras
  25752. var index2 = this.activeCameras.indexOf(toRemove);
  25753. if (index2 !== -1) {
  25754. // Remove from the scene if mesh found
  25755. this.activeCameras.splice(index2, 1);
  25756. }
  25757. // Reset the activeCamera
  25758. if (this.activeCamera === toRemove) {
  25759. if (this.cameras.length > 0) {
  25760. this.activeCamera = this.cameras[0];
  25761. }
  25762. else {
  25763. this.activeCamera = null;
  25764. }
  25765. }
  25766. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25767. return index;
  25768. };
  25769. /**
  25770. * Remove a particle system for the list of scene's particle systems
  25771. * @param toRemove defines the particle system to remove
  25772. * @returns the index where the particle system was in the particle system list
  25773. */
  25774. Scene.prototype.removeParticleSystem = function (toRemove) {
  25775. var index = this.particleSystems.indexOf(toRemove);
  25776. if (index !== -1) {
  25777. this.particleSystems.splice(index, 1);
  25778. }
  25779. return index;
  25780. };
  25781. /**
  25782. * Remove a animation for the list of scene's animations
  25783. * @param toRemove defines the animation to remove
  25784. * @returns the index where the animation was in the animation list
  25785. */
  25786. Scene.prototype.removeAnimation = function (toRemove) {
  25787. var index = this.animations.indexOf(toRemove);
  25788. if (index !== -1) {
  25789. this.animations.splice(index, 1);
  25790. }
  25791. return index;
  25792. };
  25793. /**
  25794. * Removes the given animation group from this scene.
  25795. * @param toRemove The animation group to remove
  25796. * @returns The index of the removed animation group
  25797. */
  25798. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25799. var index = this.animationGroups.indexOf(toRemove);
  25800. if (index !== -1) {
  25801. this.animationGroups.splice(index, 1);
  25802. }
  25803. return index;
  25804. };
  25805. /**
  25806. * Removes the given multi-material from this scene.
  25807. * @param toRemove The multi-material to remove
  25808. * @returns The index of the removed multi-material
  25809. */
  25810. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25811. var index = this.multiMaterials.indexOf(toRemove);
  25812. if (index !== -1) {
  25813. this.multiMaterials.splice(index, 1);
  25814. }
  25815. return index;
  25816. };
  25817. /**
  25818. * Removes the given material from this scene.
  25819. * @param toRemove The material to remove
  25820. * @returns The index of the removed material
  25821. */
  25822. Scene.prototype.removeMaterial = function (toRemove) {
  25823. var index = this.materials.indexOf(toRemove);
  25824. if (index !== -1) {
  25825. this.materials.splice(index, 1);
  25826. }
  25827. return index;
  25828. };
  25829. /**
  25830. * Removes the given lens flare system from this scene.
  25831. * @param toRemove The lens flare system to remove
  25832. * @returns The index of the removed lens flare system
  25833. */
  25834. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25835. var index = this.lensFlareSystems.indexOf(toRemove);
  25836. if (index !== -1) {
  25837. this.lensFlareSystems.splice(index, 1);
  25838. }
  25839. return index;
  25840. };
  25841. /**
  25842. * Removes the given action manager from this scene.
  25843. * @param toRemove The action manager to remove
  25844. * @returns The index of the removed action manager
  25845. */
  25846. Scene.prototype.removeActionManager = function (toRemove) {
  25847. var index = this._actionManagers.indexOf(toRemove);
  25848. if (index !== -1) {
  25849. this._actionManagers.splice(index, 1);
  25850. }
  25851. return index;
  25852. };
  25853. /**
  25854. * Removes the given effect layer from this scene.
  25855. * @param toRemove defines the effect layer to remove
  25856. * @returns the index of the removed effect layer
  25857. */
  25858. Scene.prototype.removeEffectLayer = function (toRemove) {
  25859. var index = this.effectLayers.indexOf(toRemove);
  25860. if (index !== -1) {
  25861. this.effectLayers.splice(index, 1);
  25862. }
  25863. return index;
  25864. };
  25865. /**
  25866. * Removes the given texture from this scene.
  25867. * @param toRemove The texture to remove
  25868. * @returns The index of the removed texture
  25869. */
  25870. Scene.prototype.removeTexture = function (toRemove) {
  25871. var index = this.textures.indexOf(toRemove);
  25872. if (index !== -1) {
  25873. this.textures.splice(index, 1);
  25874. }
  25875. return index;
  25876. };
  25877. /**
  25878. * Adds the given light to this scene
  25879. * @param newLight The light to add
  25880. */
  25881. Scene.prototype.addLight = function (newLight) {
  25882. this.lights.push(newLight);
  25883. this.sortLightsByPriority();
  25884. // Add light to all meshes (To support if the light is removed and then readded)
  25885. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25886. var mesh = _a[_i];
  25887. if (mesh._lightSources.indexOf(newLight) === -1) {
  25888. mesh._lightSources.push(newLight);
  25889. mesh._resyncLightSources();
  25890. }
  25891. }
  25892. this.onNewLightAddedObservable.notifyObservers(newLight);
  25893. };
  25894. /**
  25895. * Sorts the list list based on light priorities
  25896. */
  25897. Scene.prototype.sortLightsByPriority = function () {
  25898. if (this.requireLightSorting) {
  25899. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25900. }
  25901. };
  25902. /**
  25903. * Adds the given camera to this scene
  25904. * @param newCamera The camera to add
  25905. */
  25906. Scene.prototype.addCamera = function (newCamera) {
  25907. this.cameras.push(newCamera);
  25908. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25909. };
  25910. /**
  25911. * Adds the given skeleton to this scene
  25912. * @param newSkeleton The skeleton to add
  25913. */
  25914. Scene.prototype.addSkeleton = function (newSkeleton) {
  25915. this.skeletons.push(newSkeleton);
  25916. };
  25917. /**
  25918. * Adds the given particle system to this scene
  25919. * @param newParticleSystem The particle system to add
  25920. */
  25921. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25922. this.particleSystems.push(newParticleSystem);
  25923. };
  25924. /**
  25925. * Adds the given animation to this scene
  25926. * @param newAnimation The animation to add
  25927. */
  25928. Scene.prototype.addAnimation = function (newAnimation) {
  25929. this.animations.push(newAnimation);
  25930. };
  25931. /**
  25932. * Adds the given animation group to this scene.
  25933. * @param newAnimationGroup The animation group to add
  25934. */
  25935. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25936. this.animationGroups.push(newAnimationGroup);
  25937. };
  25938. /**
  25939. * Adds the given multi-material to this scene
  25940. * @param newMultiMaterial The multi-material to add
  25941. */
  25942. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25943. this.multiMaterials.push(newMultiMaterial);
  25944. };
  25945. /**
  25946. * Adds the given material to this scene
  25947. * @param newMaterial The material to add
  25948. */
  25949. Scene.prototype.addMaterial = function (newMaterial) {
  25950. this.materials.push(newMaterial);
  25951. };
  25952. /**
  25953. * Adds the given morph target to this scene
  25954. * @param newMorphTargetManager The morph target to add
  25955. */
  25956. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25957. this.morphTargetManagers.push(newMorphTargetManager);
  25958. };
  25959. /**
  25960. * Adds the given geometry to this scene
  25961. * @param newGeometry The geometry to add
  25962. */
  25963. Scene.prototype.addGeometry = function (newGeometry) {
  25964. this._geometries.push(newGeometry);
  25965. };
  25966. /**
  25967. * Adds the given lens flare system to this scene
  25968. * @param newLensFlareSystem The lens flare system to add
  25969. */
  25970. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25971. this.lensFlareSystems.push(newLensFlareSystem);
  25972. };
  25973. /**
  25974. * Adds the given effect layer to this scene
  25975. * @param newEffectLayer defines the effect layer to add
  25976. */
  25977. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25978. this.effectLayers.push(newEffectLayer);
  25979. };
  25980. /**
  25981. * Adds the given action manager to this scene
  25982. * @param newActionManager The action manager to add
  25983. */
  25984. Scene.prototype.addActionManager = function (newActionManager) {
  25985. this._actionManagers.push(newActionManager);
  25986. };
  25987. /**
  25988. * Adds the given texture to this scene.
  25989. * @param newTexture The texture to add
  25990. */
  25991. Scene.prototype.addTexture = function (newTexture) {
  25992. this.textures.push(newTexture);
  25993. };
  25994. /**
  25995. * Switch active camera
  25996. * @param newCamera defines the new active camera
  25997. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25998. */
  25999. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26000. if (attachControl === void 0) { attachControl = true; }
  26001. var canvas = this._engine.getRenderingCanvas();
  26002. if (!canvas) {
  26003. return;
  26004. }
  26005. if (this.activeCamera) {
  26006. this.activeCamera.detachControl(canvas);
  26007. }
  26008. this.activeCamera = newCamera;
  26009. if (attachControl) {
  26010. newCamera.attachControl(canvas);
  26011. }
  26012. };
  26013. /**
  26014. * sets the active camera of the scene using its ID
  26015. * @param id defines the camera's ID
  26016. * @return the new active camera or null if none found.
  26017. */
  26018. Scene.prototype.setActiveCameraByID = function (id) {
  26019. var camera = this.getCameraByID(id);
  26020. if (camera) {
  26021. this.activeCamera = camera;
  26022. return camera;
  26023. }
  26024. return null;
  26025. };
  26026. /**
  26027. * sets the active camera of the scene using its name
  26028. * @param name defines the camera's name
  26029. * @returns the new active camera or null if none found.
  26030. */
  26031. Scene.prototype.setActiveCameraByName = function (name) {
  26032. var camera = this.getCameraByName(name);
  26033. if (camera) {
  26034. this.activeCamera = camera;
  26035. return camera;
  26036. }
  26037. return null;
  26038. };
  26039. /**
  26040. * get an animation group using its name
  26041. * @param name defines the material's name
  26042. * @return the animation group or null if none found.
  26043. */
  26044. Scene.prototype.getAnimationGroupByName = function (name) {
  26045. for (var index = 0; index < this.animationGroups.length; index++) {
  26046. if (this.animationGroups[index].name === name) {
  26047. return this.animationGroups[index];
  26048. }
  26049. }
  26050. return null;
  26051. };
  26052. /**
  26053. * get a material using its id
  26054. * @param id defines the material's ID
  26055. * @return the material or null if none found.
  26056. */
  26057. Scene.prototype.getMaterialByID = function (id) {
  26058. for (var index = 0; index < this.materials.length; index++) {
  26059. if (this.materials[index].id === id) {
  26060. return this.materials[index];
  26061. }
  26062. }
  26063. return null;
  26064. };
  26065. /**
  26066. * Gets a material using its name
  26067. * @param name defines the material's name
  26068. * @return the material or null if none found.
  26069. */
  26070. Scene.prototype.getMaterialByName = function (name) {
  26071. for (var index = 0; index < this.materials.length; index++) {
  26072. if (this.materials[index].name === name) {
  26073. return this.materials[index];
  26074. }
  26075. }
  26076. return null;
  26077. };
  26078. /**
  26079. * Gets a lens flare system using its name
  26080. * @param name defines the name to look for
  26081. * @returns the lens flare system or null if not found
  26082. */
  26083. Scene.prototype.getLensFlareSystemByName = function (name) {
  26084. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26085. if (this.lensFlareSystems[index].name === name) {
  26086. return this.lensFlareSystems[index];
  26087. }
  26088. }
  26089. return null;
  26090. };
  26091. /**
  26092. * Gets a lens flare system using its id
  26093. * @param id defines the id to look for
  26094. * @returns the lens flare system or null if not found
  26095. */
  26096. Scene.prototype.getLensFlareSystemByID = function (id) {
  26097. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26098. if (this.lensFlareSystems[index].id === id) {
  26099. return this.lensFlareSystems[index];
  26100. }
  26101. }
  26102. return null;
  26103. };
  26104. /**
  26105. * Gets a camera using its id
  26106. * @param id defines the id to look for
  26107. * @returns the camera or null if not found
  26108. */
  26109. Scene.prototype.getCameraByID = function (id) {
  26110. for (var index = 0; index < this.cameras.length; index++) {
  26111. if (this.cameras[index].id === id) {
  26112. return this.cameras[index];
  26113. }
  26114. }
  26115. return null;
  26116. };
  26117. /**
  26118. * Gets a camera using its unique id
  26119. * @param uniqueId defines the unique id to look for
  26120. * @returns the camera or null if not found
  26121. */
  26122. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26123. for (var index = 0; index < this.cameras.length; index++) {
  26124. if (this.cameras[index].uniqueId === uniqueId) {
  26125. return this.cameras[index];
  26126. }
  26127. }
  26128. return null;
  26129. };
  26130. /**
  26131. * Gets a camera using its name
  26132. * @param name defines the camera's name
  26133. * @return the camera or null if none found.
  26134. */
  26135. Scene.prototype.getCameraByName = function (name) {
  26136. for (var index = 0; index < this.cameras.length; index++) {
  26137. if (this.cameras[index].name === name) {
  26138. return this.cameras[index];
  26139. }
  26140. }
  26141. return null;
  26142. };
  26143. /**
  26144. * Gets a bone using its id
  26145. * @param id defines the bone's id
  26146. * @return the bone or null if not found
  26147. */
  26148. Scene.prototype.getBoneByID = function (id) {
  26149. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26150. var skeleton = this.skeletons[skeletonIndex];
  26151. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26152. if (skeleton.bones[boneIndex].id === id) {
  26153. return skeleton.bones[boneIndex];
  26154. }
  26155. }
  26156. }
  26157. return null;
  26158. };
  26159. /**
  26160. * Gets a bone using its id
  26161. * @param name defines the bone's name
  26162. * @return the bone or null if not found
  26163. */
  26164. Scene.prototype.getBoneByName = function (name) {
  26165. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26166. var skeleton = this.skeletons[skeletonIndex];
  26167. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26168. if (skeleton.bones[boneIndex].name === name) {
  26169. return skeleton.bones[boneIndex];
  26170. }
  26171. }
  26172. }
  26173. return null;
  26174. };
  26175. /**
  26176. * Gets a light node using its name
  26177. * @param name defines the the light's name
  26178. * @return the light or null if none found.
  26179. */
  26180. Scene.prototype.getLightByName = function (name) {
  26181. for (var index = 0; index < this.lights.length; index++) {
  26182. if (this.lights[index].name === name) {
  26183. return this.lights[index];
  26184. }
  26185. }
  26186. return null;
  26187. };
  26188. /**
  26189. * Gets a light node using its id
  26190. * @param id defines the light's id
  26191. * @return the light or null if none found.
  26192. */
  26193. Scene.prototype.getLightByID = function (id) {
  26194. for (var index = 0; index < this.lights.length; index++) {
  26195. if (this.lights[index].id === id) {
  26196. return this.lights[index];
  26197. }
  26198. }
  26199. return null;
  26200. };
  26201. /**
  26202. * Gets a light node using its scene-generated unique ID
  26203. * @param uniqueId defines the light's unique id
  26204. * @return the light or null if none found.
  26205. */
  26206. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26207. for (var index = 0; index < this.lights.length; index++) {
  26208. if (this.lights[index].uniqueId === uniqueId) {
  26209. return this.lights[index];
  26210. }
  26211. }
  26212. return null;
  26213. };
  26214. /**
  26215. * Gets a particle system by id
  26216. * @param id defines the particle system id
  26217. * @return the corresponding system or null if none found
  26218. */
  26219. Scene.prototype.getParticleSystemByID = function (id) {
  26220. for (var index = 0; index < this.particleSystems.length; index++) {
  26221. if (this.particleSystems[index].id === id) {
  26222. return this.particleSystems[index];
  26223. }
  26224. }
  26225. return null;
  26226. };
  26227. /**
  26228. * Gets a geometry using its ID
  26229. * @param id defines the geometry's id
  26230. * @return the geometry or null if none found.
  26231. */
  26232. Scene.prototype.getGeometryByID = function (id) {
  26233. for (var index = 0; index < this._geometries.length; index++) {
  26234. if (this._geometries[index].id === id) {
  26235. return this._geometries[index];
  26236. }
  26237. }
  26238. return null;
  26239. };
  26240. /**
  26241. * Add a new geometry to this scene
  26242. * @param geometry defines the geometry to be added to the scene.
  26243. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26244. * @return a boolean defining if the geometry was added or not
  26245. */
  26246. Scene.prototype.pushGeometry = function (geometry, force) {
  26247. if (!force && this.getGeometryByID(geometry.id)) {
  26248. return false;
  26249. }
  26250. this._geometries.push(geometry);
  26251. //notify the collision coordinator
  26252. if (this.collisionCoordinator) {
  26253. this.collisionCoordinator.onGeometryAdded(geometry);
  26254. }
  26255. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26256. return true;
  26257. };
  26258. /**
  26259. * Removes an existing geometry
  26260. * @param geometry defines the geometry to be removed from the scene
  26261. * @return a boolean defining if the geometry was removed or not
  26262. */
  26263. Scene.prototype.removeGeometry = function (geometry) {
  26264. var index = this._geometries.indexOf(geometry);
  26265. if (index > -1) {
  26266. this._geometries.splice(index, 1);
  26267. //notify the collision coordinator
  26268. if (this.collisionCoordinator) {
  26269. this.collisionCoordinator.onGeometryDeleted(geometry);
  26270. }
  26271. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26272. return true;
  26273. }
  26274. return false;
  26275. };
  26276. /**
  26277. * Gets the list of geometries attached to the scene
  26278. * @returns an array of Geometry
  26279. */
  26280. Scene.prototype.getGeometries = function () {
  26281. return this._geometries;
  26282. };
  26283. /**
  26284. * Gets the first added mesh found of a given ID
  26285. * @param id defines the id to search for
  26286. * @return the mesh found or null if not found at all
  26287. */
  26288. Scene.prototype.getMeshByID = function (id) {
  26289. for (var index = 0; index < this.meshes.length; index++) {
  26290. if (this.meshes[index].id === id) {
  26291. return this.meshes[index];
  26292. }
  26293. }
  26294. return null;
  26295. };
  26296. /**
  26297. * Gets a list of meshes using their id
  26298. * @param id defines the id to search for
  26299. * @returns a list of meshes
  26300. */
  26301. Scene.prototype.getMeshesByID = function (id) {
  26302. return this.meshes.filter(function (m) {
  26303. return m.id === id;
  26304. });
  26305. };
  26306. /**
  26307. * Gets the first added transform node found of a given ID
  26308. * @param id defines the id to search for
  26309. * @return the found transform node or null if not found at all.
  26310. */
  26311. Scene.prototype.getTransformNodeByID = function (id) {
  26312. for (var index = 0; index < this.transformNodes.length; index++) {
  26313. if (this.transformNodes[index].id === id) {
  26314. return this.transformNodes[index];
  26315. }
  26316. }
  26317. return null;
  26318. };
  26319. /**
  26320. * Gets a list of transform nodes using their id
  26321. * @param id defines the id to search for
  26322. * @returns a list of transform nodes
  26323. */
  26324. Scene.prototype.getTransformNodesByID = function (id) {
  26325. return this.transformNodes.filter(function (m) {
  26326. return m.id === id;
  26327. });
  26328. };
  26329. /**
  26330. * Gets a mesh with its auto-generated unique id
  26331. * @param uniqueId defines the unique id to search for
  26332. * @return the found mesh or null if not found at all.
  26333. */
  26334. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26335. for (var index = 0; index < this.meshes.length; index++) {
  26336. if (this.meshes[index].uniqueId === uniqueId) {
  26337. return this.meshes[index];
  26338. }
  26339. }
  26340. return null;
  26341. };
  26342. /**
  26343. * Gets a the last added mesh using a given id
  26344. * @param id defines the id to search for
  26345. * @return the found mesh or null if not found at all.
  26346. */
  26347. Scene.prototype.getLastMeshByID = function (id) {
  26348. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26349. if (this.meshes[index].id === id) {
  26350. return this.meshes[index];
  26351. }
  26352. }
  26353. return null;
  26354. };
  26355. /**
  26356. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26357. * @param id defines the id to search for
  26358. * @return the found node or null if not found at all
  26359. */
  26360. Scene.prototype.getLastEntryByID = function (id) {
  26361. var index;
  26362. for (index = this.meshes.length - 1; index >= 0; index--) {
  26363. if (this.meshes[index].id === id) {
  26364. return this.meshes[index];
  26365. }
  26366. }
  26367. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26368. if (this.transformNodes[index].id === id) {
  26369. return this.transformNodes[index];
  26370. }
  26371. }
  26372. for (index = this.cameras.length - 1; index >= 0; index--) {
  26373. if (this.cameras[index].id === id) {
  26374. return this.cameras[index];
  26375. }
  26376. }
  26377. for (index = this.lights.length - 1; index >= 0; index--) {
  26378. if (this.lights[index].id === id) {
  26379. return this.lights[index];
  26380. }
  26381. }
  26382. return null;
  26383. };
  26384. /**
  26385. * Gets a node (Mesh, Camera, Light) using a given id
  26386. * @param id defines the id to search for
  26387. * @return the found node or null if not found at all
  26388. */
  26389. Scene.prototype.getNodeByID = function (id) {
  26390. var mesh = this.getMeshByID(id);
  26391. if (mesh) {
  26392. return mesh;
  26393. }
  26394. var light = this.getLightByID(id);
  26395. if (light) {
  26396. return light;
  26397. }
  26398. var camera = this.getCameraByID(id);
  26399. if (camera) {
  26400. return camera;
  26401. }
  26402. var bone = this.getBoneByID(id);
  26403. return bone;
  26404. };
  26405. /**
  26406. * Gets a node (Mesh, Camera, Light) using a given name
  26407. * @param name defines the name to search for
  26408. * @return the found node or null if not found at all.
  26409. */
  26410. Scene.prototype.getNodeByName = function (name) {
  26411. var mesh = this.getMeshByName(name);
  26412. if (mesh) {
  26413. return mesh;
  26414. }
  26415. var light = this.getLightByName(name);
  26416. if (light) {
  26417. return light;
  26418. }
  26419. var camera = this.getCameraByName(name);
  26420. if (camera) {
  26421. return camera;
  26422. }
  26423. var bone = this.getBoneByName(name);
  26424. return bone;
  26425. };
  26426. /**
  26427. * Gets a mesh using a given name
  26428. * @param name defines the name to search for
  26429. * @return the found mesh or null if not found at all.
  26430. */
  26431. Scene.prototype.getMeshByName = function (name) {
  26432. for (var index = 0; index < this.meshes.length; index++) {
  26433. if (this.meshes[index].name === name) {
  26434. return this.meshes[index];
  26435. }
  26436. }
  26437. return null;
  26438. };
  26439. /**
  26440. * Gets a transform node using a given name
  26441. * @param name defines the name to search for
  26442. * @return the found transform node or null if not found at all.
  26443. */
  26444. Scene.prototype.getTransformNodeByName = function (name) {
  26445. for (var index = 0; index < this.transformNodes.length; index++) {
  26446. if (this.transformNodes[index].name === name) {
  26447. return this.transformNodes[index];
  26448. }
  26449. }
  26450. return null;
  26451. };
  26452. /**
  26453. * Gets a sound using a given name
  26454. * @param name defines the name to search for
  26455. * @return the found sound or null if not found at all.
  26456. */
  26457. Scene.prototype.getSoundByName = function (name) {
  26458. var index;
  26459. if (BABYLON.AudioEngine) {
  26460. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26461. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26462. return this.mainSoundTrack.soundCollection[index];
  26463. }
  26464. }
  26465. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26466. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26467. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26468. return this.soundTracks[sdIndex].soundCollection[index];
  26469. }
  26470. }
  26471. }
  26472. }
  26473. return null;
  26474. };
  26475. /**
  26476. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26477. * @param id defines the id to search for
  26478. * @return the found skeleton or null if not found at all.
  26479. */
  26480. Scene.prototype.getLastSkeletonByID = function (id) {
  26481. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26482. if (this.skeletons[index].id === id) {
  26483. return this.skeletons[index];
  26484. }
  26485. }
  26486. return null;
  26487. };
  26488. /**
  26489. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26490. * @param id defines the id to search for
  26491. * @return the found skeleton or null if not found at all.
  26492. */
  26493. Scene.prototype.getSkeletonById = function (id) {
  26494. for (var index = 0; index < this.skeletons.length; index++) {
  26495. if (this.skeletons[index].id === id) {
  26496. return this.skeletons[index];
  26497. }
  26498. }
  26499. return null;
  26500. };
  26501. /**
  26502. * Gets a skeleton using a given name
  26503. * @param name defines the name to search for
  26504. * @return the found skeleton or null if not found at all.
  26505. */
  26506. Scene.prototype.getSkeletonByName = function (name) {
  26507. for (var index = 0; index < this.skeletons.length; index++) {
  26508. if (this.skeletons[index].name === name) {
  26509. return this.skeletons[index];
  26510. }
  26511. }
  26512. return null;
  26513. };
  26514. /**
  26515. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26516. * @param id defines the id to search for
  26517. * @return the found morph target manager or null if not found at all.
  26518. */
  26519. Scene.prototype.getMorphTargetManagerById = function (id) {
  26520. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26521. if (this.morphTargetManagers[index].uniqueId === id) {
  26522. return this.morphTargetManagers[index];
  26523. }
  26524. }
  26525. return null;
  26526. };
  26527. /**
  26528. * Gets a boolean indicating if the given mesh is active
  26529. * @param mesh defines the mesh to look for
  26530. * @returns true if the mesh is in the active list
  26531. */
  26532. Scene.prototype.isActiveMesh = function (mesh) {
  26533. return (this._activeMeshes.indexOf(mesh) !== -1);
  26534. };
  26535. /**
  26536. * Return a the first highlight layer of the scene with a given name.
  26537. * @param name The name of the highlight layer to look for.
  26538. * @return The highlight layer if found otherwise null.
  26539. */
  26540. Scene.prototype.getHighlightLayerByName = function (name) {
  26541. for (var index = 0; index < this.effectLayers.length; index++) {
  26542. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26543. return this.effectLayers[index];
  26544. }
  26545. }
  26546. return null;
  26547. };
  26548. /**
  26549. * Return a the first highlight layer of the scene with a given name.
  26550. * @param name The name of the highlight layer to look for.
  26551. * @return The highlight layer if found otherwise null.
  26552. */
  26553. Scene.prototype.getGlowLayerByName = function (name) {
  26554. for (var index = 0; index < this.effectLayers.length; index++) {
  26555. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26556. return this.effectLayers[index];
  26557. }
  26558. }
  26559. return null;
  26560. };
  26561. Object.defineProperty(Scene.prototype, "uid", {
  26562. /**
  26563. * Return a unique id as a string which can serve as an identifier for the scene
  26564. */
  26565. get: function () {
  26566. if (!this._uid) {
  26567. this._uid = BABYLON.Tools.RandomId();
  26568. }
  26569. return this._uid;
  26570. },
  26571. enumerable: true,
  26572. configurable: true
  26573. });
  26574. /**
  26575. * Add an externaly attached data from its key.
  26576. * This method call will fail and return false, if such key already exists.
  26577. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26578. * @param key the unique key that identifies the data
  26579. * @param data the data object to associate to the key for this Engine instance
  26580. * @return true if no such key were already present and the data was added successfully, false otherwise
  26581. */
  26582. Scene.prototype.addExternalData = function (key, data) {
  26583. if (!this._externalData) {
  26584. this._externalData = new BABYLON.StringDictionary();
  26585. }
  26586. return this._externalData.add(key, data);
  26587. };
  26588. /**
  26589. * Get an externaly attached data from its key
  26590. * @param key the unique key that identifies the data
  26591. * @return the associated data, if present (can be null), or undefined if not present
  26592. */
  26593. Scene.prototype.getExternalData = function (key) {
  26594. if (!this._externalData) {
  26595. return null;
  26596. }
  26597. return this._externalData.get(key);
  26598. };
  26599. /**
  26600. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26601. * @param key the unique key that identifies the data
  26602. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26603. * @return the associated data, can be null if the factory returned null.
  26604. */
  26605. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26606. if (!this._externalData) {
  26607. this._externalData = new BABYLON.StringDictionary();
  26608. }
  26609. return this._externalData.getOrAddWithFactory(key, factory);
  26610. };
  26611. /**
  26612. * Remove an externaly attached data from the Engine instance
  26613. * @param key the unique key that identifies the data
  26614. * @return true if the data was successfully removed, false if it doesn't exist
  26615. */
  26616. Scene.prototype.removeExternalData = function (key) {
  26617. return this._externalData.remove(key);
  26618. };
  26619. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26620. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26621. if (mesh.showSubMeshesBoundingBox) {
  26622. var boundingInfo = subMesh.getBoundingInfo();
  26623. if (boundingInfo !== null && boundingInfo !== undefined) {
  26624. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26625. }
  26626. }
  26627. var material = subMesh.getMaterial();
  26628. if (material !== null && material !== undefined) {
  26629. // Render targets
  26630. if (material.getRenderTargetTextures !== undefined) {
  26631. if (this._processedMaterials.indexOf(material) === -1) {
  26632. this._processedMaterials.push(material);
  26633. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26634. }
  26635. }
  26636. // Dispatch
  26637. this._activeIndices.addCount(subMesh.indexCount, false);
  26638. this._renderingManager.dispatch(subMesh, mesh, material);
  26639. }
  26640. }
  26641. };
  26642. /**
  26643. * Clear the processed materials smart array preventing retention point in material dispose.
  26644. */
  26645. Scene.prototype.freeProcessedMaterials = function () {
  26646. this._processedMaterials.dispose();
  26647. };
  26648. /**
  26649. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26650. */
  26651. Scene.prototype.freeActiveMeshes = function () {
  26652. this._activeMeshes.dispose();
  26653. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26654. this.activeCamera._activeMeshes.dispose();
  26655. }
  26656. if (this.activeCameras) {
  26657. for (var i = 0; i < this.activeCameras.length; i++) {
  26658. var activeCamera = this.activeCameras[i];
  26659. if (activeCamera && activeCamera._activeMeshes) {
  26660. activeCamera._activeMeshes.dispose();
  26661. }
  26662. }
  26663. }
  26664. };
  26665. /**
  26666. * Clear the info related to rendering groups preventing retention points during dispose.
  26667. */
  26668. Scene.prototype.freeRenderingGroups = function () {
  26669. if (this._renderingManager) {
  26670. this._renderingManager.freeRenderingGroups();
  26671. }
  26672. if (this.textures) {
  26673. for (var i = 0; i < this.textures.length; i++) {
  26674. var texture = this.textures[i];
  26675. if (texture && texture.renderList) {
  26676. texture.freeRenderingGroups();
  26677. }
  26678. }
  26679. }
  26680. };
  26681. /** @ignore */
  26682. Scene.prototype._isInIntermediateRendering = function () {
  26683. return this._intermediateRendering;
  26684. };
  26685. /**
  26686. * Defines the current active mesh candidate provider
  26687. * @param provider defines the provider to use
  26688. */
  26689. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26690. this._activeMeshCandidateProvider = provider;
  26691. };
  26692. /**
  26693. * Gets the current active mesh candidate provider
  26694. * @returns the current active mesh candidate provider
  26695. */
  26696. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26697. return this._activeMeshCandidateProvider;
  26698. };
  26699. /**
  26700. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26701. * @returns the current scene
  26702. */
  26703. Scene.prototype.freezeActiveMeshes = function () {
  26704. if (!this.activeCamera) {
  26705. return this;
  26706. }
  26707. if (!this._frustumPlanes) {
  26708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26709. }
  26710. this._evaluateActiveMeshes();
  26711. this._activeMeshesFrozen = true;
  26712. return this;
  26713. };
  26714. /**
  26715. * Use this function to restart evaluating active meshes on every frame
  26716. * @returns the current scene
  26717. */
  26718. Scene.prototype.unfreezeActiveMeshes = function () {
  26719. this._activeMeshesFrozen = false;
  26720. return this;
  26721. };
  26722. Scene.prototype._evaluateActiveMeshes = function () {
  26723. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26724. return;
  26725. }
  26726. if (!this.activeCamera) {
  26727. return;
  26728. }
  26729. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26730. this.activeCamera._activeMeshes.reset();
  26731. this._activeMeshes.reset();
  26732. this._renderingManager.reset();
  26733. this._processedMaterials.reset();
  26734. this._activeParticleSystems.reset();
  26735. this._activeSkeletons.reset();
  26736. this._softwareSkinnedMeshes.reset();
  26737. if (this._boundingBoxRenderer) {
  26738. this._boundingBoxRenderer.reset();
  26739. }
  26740. // Meshes
  26741. var meshes;
  26742. var len;
  26743. var checkIsEnabled = true;
  26744. // Determine mesh candidates
  26745. if (this._activeMeshCandidateProvider !== undefined) {
  26746. // Use _activeMeshCandidateProvider
  26747. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26748. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26749. if (meshes !== undefined) {
  26750. len = meshes.length;
  26751. }
  26752. else {
  26753. len = 0;
  26754. }
  26755. }
  26756. else if (this._selectionOctree !== undefined) {
  26757. // Octree
  26758. var selection = this._selectionOctree.select(this._frustumPlanes);
  26759. meshes = selection.data;
  26760. len = selection.length;
  26761. }
  26762. else {
  26763. // Full scene traversal
  26764. len = this.meshes.length;
  26765. meshes = this.meshes;
  26766. }
  26767. // Check each mesh
  26768. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26769. mesh = meshes[meshIndex];
  26770. if (mesh.isBlocked) {
  26771. continue;
  26772. }
  26773. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26774. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26775. continue;
  26776. }
  26777. mesh.computeWorldMatrix();
  26778. // Intersections
  26779. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26780. this._meshesForIntersections.pushNoDuplicate(mesh);
  26781. }
  26782. // Switch to current LOD
  26783. meshLOD = mesh.getLOD(this.activeCamera);
  26784. if (meshLOD === undefined || meshLOD === null) {
  26785. continue;
  26786. }
  26787. mesh._preActivate();
  26788. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26789. this._activeMeshes.push(mesh);
  26790. this.activeCamera._activeMeshes.push(mesh);
  26791. mesh._activate(this._renderId);
  26792. if (meshLOD !== mesh) {
  26793. meshLOD._activate(this._renderId);
  26794. }
  26795. this._activeMesh(mesh, meshLOD);
  26796. }
  26797. }
  26798. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26799. // Particle systems
  26800. if (this.particlesEnabled) {
  26801. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26802. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26803. var particleSystem = this.particleSystems[particleIndex];
  26804. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26805. continue;
  26806. }
  26807. var emitter = particleSystem.emitter;
  26808. if (!emitter.position || emitter.isEnabled()) {
  26809. this._activeParticleSystems.push(particleSystem);
  26810. particleSystem.animate();
  26811. this._renderingManager.dispatchParticles(particleSystem);
  26812. }
  26813. }
  26814. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26815. }
  26816. };
  26817. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26818. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26819. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26820. mesh.skeleton.prepare();
  26821. }
  26822. if (!mesh.computeBonesUsingShaders) {
  26823. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26824. }
  26825. }
  26826. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26827. var boundingInfo = sourceMesh.getBoundingInfo();
  26828. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26829. }
  26830. if (mesh !== undefined && mesh !== null
  26831. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26832. // Submeshes Octrees
  26833. var len;
  26834. var subMeshes;
  26835. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26836. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26837. len = intersections.length;
  26838. subMeshes = intersections.data;
  26839. }
  26840. else {
  26841. subMeshes = mesh.subMeshes;
  26842. len = subMeshes.length;
  26843. }
  26844. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26845. subMesh = subMeshes[subIndex];
  26846. this._evaluateSubMesh(subMesh, mesh);
  26847. }
  26848. }
  26849. };
  26850. /**
  26851. * Update the transform matrix to update from the current active camera
  26852. * @param force defines a boolean used to force the update even if cache is up to date
  26853. */
  26854. Scene.prototype.updateTransformMatrix = function (force) {
  26855. if (!this.activeCamera) {
  26856. return;
  26857. }
  26858. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26859. };
  26860. /**
  26861. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  26862. * @param alternateCamera defines the camera to use
  26863. */
  26864. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26865. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26866. };
  26867. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26868. if (camera && camera._skipRendering) {
  26869. return;
  26870. }
  26871. var engine = this._engine;
  26872. this.activeCamera = camera;
  26873. if (!this.activeCamera)
  26874. throw new Error("Active camera not set");
  26875. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26876. // Viewport
  26877. engine.setViewport(this.activeCamera.viewport);
  26878. // Camera
  26879. this.resetCachedMaterial();
  26880. this._renderId++;
  26881. this.updateTransformMatrix();
  26882. if (camera._alternateCamera) {
  26883. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26884. this._alternateRendering = true;
  26885. }
  26886. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26887. // Meshes
  26888. this._evaluateActiveMeshes();
  26889. // Software skinning
  26890. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26891. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26892. mesh.applySkeleton(mesh.skeleton);
  26893. }
  26894. // Render targets
  26895. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26896. var needsRestoreFrameBuffer = false;
  26897. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26898. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26899. }
  26900. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26901. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26902. }
  26903. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26904. this._intermediateRendering = true;
  26905. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26906. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26907. var renderTarget = this._renderTargets.data[renderIndex];
  26908. if (renderTarget._shouldRender()) {
  26909. this._renderId++;
  26910. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26911. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26912. }
  26913. }
  26914. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26915. this._intermediateRendering = false;
  26916. this._renderId++;
  26917. needsRestoreFrameBuffer = true; // Restore back buffer
  26918. }
  26919. // Render EffecttLayer Texture
  26920. var stencilState = this._engine.getStencilBuffer();
  26921. var renderEffects = false;
  26922. var needStencil = false;
  26923. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26924. this._intermediateRendering = true;
  26925. for (var i = 0; i < this.effectLayers.length; i++) {
  26926. var effectLayer = this.effectLayers[i];
  26927. if (effectLayer.shouldRender() &&
  26928. (!effectLayer.camera ||
  26929. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26930. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26931. renderEffects = true;
  26932. needStencil = needStencil || effectLayer.needStencil();
  26933. var renderTarget = effectLayer._mainTexture;
  26934. if (renderTarget._shouldRender()) {
  26935. this._renderId++;
  26936. renderTarget.render(false, false);
  26937. needsRestoreFrameBuffer = true;
  26938. }
  26939. }
  26940. }
  26941. this._intermediateRendering = false;
  26942. this._renderId++;
  26943. }
  26944. if (needsRestoreFrameBuffer) {
  26945. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26946. }
  26947. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26948. // Prepare Frame
  26949. this.postProcessManager._prepareFrame();
  26950. // Backgrounds
  26951. var layerIndex;
  26952. var layer;
  26953. if (this.layers.length) {
  26954. engine.setDepthBuffer(false);
  26955. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26956. layer = this.layers[layerIndex];
  26957. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26958. layer.render();
  26959. }
  26960. }
  26961. engine.setDepthBuffer(true);
  26962. }
  26963. // Activate effect Layer stencil
  26964. if (needStencil) {
  26965. this._engine.setStencilBuffer(true);
  26966. }
  26967. // Render
  26968. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26969. this._renderingManager.render(null, null, true, true);
  26970. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26971. // Restore effect Layer stencil
  26972. if (needStencil) {
  26973. this._engine.setStencilBuffer(stencilState);
  26974. }
  26975. // Bounding boxes
  26976. if (this._boundingBoxRenderer) {
  26977. this._boundingBoxRenderer.render();
  26978. }
  26979. // Lens flares
  26980. if (this.lensFlaresEnabled) {
  26981. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26982. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26983. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26984. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26985. lensFlareSystem.render();
  26986. }
  26987. }
  26988. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26989. }
  26990. // Effect Layer
  26991. if (renderEffects) {
  26992. engine.setDepthBuffer(false);
  26993. for (var i = 0; i < this.effectLayers.length; i++) {
  26994. if (this.effectLayers[i].shouldRender()) {
  26995. this.effectLayers[i].render();
  26996. }
  26997. }
  26998. engine.setDepthBuffer(true);
  26999. }
  27000. // Foregrounds
  27001. if (this.layers.length) {
  27002. engine.setDepthBuffer(false);
  27003. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27004. layer = this.layers[layerIndex];
  27005. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27006. layer.render();
  27007. }
  27008. }
  27009. engine.setDepthBuffer(true);
  27010. }
  27011. // Finalize frame
  27012. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27013. // Reset some special arrays
  27014. this._renderTargets.reset();
  27015. this._alternateRendering = false;
  27016. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27017. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27018. };
  27019. Scene.prototype._processSubCameras = function (camera) {
  27020. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27021. this._renderForCamera(camera);
  27022. return;
  27023. }
  27024. // rig cameras
  27025. for (var index = 0; index < camera._rigCameras.length; index++) {
  27026. this._renderForCamera(camera._rigCameras[index], camera);
  27027. }
  27028. this.activeCamera = camera;
  27029. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27030. };
  27031. Scene.prototype._checkIntersections = function () {
  27032. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27033. var sourceMesh = this._meshesForIntersections.data[index];
  27034. if (!sourceMesh.actionManager) {
  27035. continue;
  27036. }
  27037. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27038. var action = sourceMesh.actionManager.actions[actionIndex];
  27039. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27040. var parameters = action.getTriggerParameter();
  27041. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27042. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27043. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27044. if (areIntersecting && currentIntersectionInProgress === -1) {
  27045. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27046. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27047. sourceMesh._intersectionsInProgress.push(otherMesh);
  27048. }
  27049. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27050. sourceMesh._intersectionsInProgress.push(otherMesh);
  27051. }
  27052. }
  27053. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27054. //They intersected, and now they don't.
  27055. //is this trigger an exit trigger? execute an event.
  27056. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27057. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27058. }
  27059. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27060. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27061. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27062. return otherMesh === parameterMesh;
  27063. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27064. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27065. }
  27066. }
  27067. }
  27068. }
  27069. }
  27070. };
  27071. /**
  27072. * Render the scene
  27073. */
  27074. Scene.prototype.render = function () {
  27075. if (this.isDisposed) {
  27076. return;
  27077. }
  27078. this._activeParticles.fetchNewFrame();
  27079. this._totalVertices.fetchNewFrame();
  27080. this._activeIndices.fetchNewFrame();
  27081. this._activeBones.fetchNewFrame();
  27082. this._meshesForIntersections.reset();
  27083. this.resetCachedMaterial();
  27084. this.onBeforeAnimationsObservable.notifyObservers(this);
  27085. // Actions
  27086. if (this.actionManager) {
  27087. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27088. }
  27089. //Simplification Queue
  27090. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27091. this.simplificationQueue.executeNext();
  27092. }
  27093. if (this._engine.isDeterministicLockStep()) {
  27094. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27095. var defaultFPS = (60.0 / 1000.0);
  27096. var defaultFrameTime = 1000 / 60; // frame time in MS
  27097. if (this._physicsEngine) {
  27098. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27099. }
  27100. var stepsTaken = 0;
  27101. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27102. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27103. internalSteps = Math.min(internalSteps, maxSubSteps);
  27104. do {
  27105. this.onBeforeStepObservable.notifyObservers(this);
  27106. // Animations
  27107. this._animationRatio = defaultFrameTime * defaultFPS;
  27108. this._animate();
  27109. this.onAfterAnimationsObservable.notifyObservers(this);
  27110. // Physics
  27111. if (this._physicsEngine) {
  27112. this.onBeforePhysicsObservable.notifyObservers(this);
  27113. this._physicsEngine._step(defaultFrameTime / 1000);
  27114. this.onAfterPhysicsObservable.notifyObservers(this);
  27115. }
  27116. this.onAfterStepObservable.notifyObservers(this);
  27117. this._currentStepId++;
  27118. stepsTaken++;
  27119. deltaTime -= defaultFrameTime;
  27120. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27121. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27122. }
  27123. else {
  27124. // Animations
  27125. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27126. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27127. this._animate();
  27128. this.onAfterAnimationsObservable.notifyObservers(this);
  27129. // Physics
  27130. if (this._physicsEngine) {
  27131. this.onBeforePhysicsObservable.notifyObservers(this);
  27132. this._physicsEngine._step(deltaTime / 1000.0);
  27133. this.onAfterPhysicsObservable.notifyObservers(this);
  27134. }
  27135. }
  27136. // update gamepad manager
  27137. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27138. this._gamepadManager._checkGamepadsStatus();
  27139. }
  27140. // Update Cameras
  27141. if (this.activeCameras.length > 0) {
  27142. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27143. var camera = this.activeCameras[cameraIndex];
  27144. camera.update();
  27145. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27146. // rig cameras
  27147. for (var index = 0; index < camera._rigCameras.length; index++) {
  27148. camera._rigCameras[index].update();
  27149. }
  27150. }
  27151. }
  27152. }
  27153. else if (this.activeCamera) {
  27154. this.activeCamera.update();
  27155. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27156. // rig cameras
  27157. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27158. this.activeCamera._rigCameras[index].update();
  27159. }
  27160. }
  27161. }
  27162. // Before render
  27163. this.onBeforeRenderObservable.notifyObservers(this);
  27164. // Customs render targets
  27165. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27166. var engine = this.getEngine();
  27167. var currentActiveCamera = this.activeCamera;
  27168. if (this.renderTargetsEnabled) {
  27169. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27170. this._intermediateRendering = true;
  27171. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27172. var renderTarget = this.customRenderTargets[customIndex];
  27173. if (renderTarget._shouldRender()) {
  27174. this._renderId++;
  27175. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27176. if (!this.activeCamera)
  27177. throw new Error("Active camera not set");
  27178. // Viewport
  27179. engine.setViewport(this.activeCamera.viewport);
  27180. // Camera
  27181. this.updateTransformMatrix();
  27182. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27183. }
  27184. }
  27185. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27186. this._intermediateRendering = false;
  27187. this._renderId++;
  27188. }
  27189. // Restore back buffer
  27190. if (this.customRenderTargets.length > 0) {
  27191. engine.restoreDefaultFramebuffer();
  27192. }
  27193. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27194. this.activeCamera = currentActiveCamera;
  27195. // Procedural textures
  27196. if (this.proceduralTexturesEnabled) {
  27197. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27198. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27199. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27200. if (proceduralTexture._shouldRender()) {
  27201. proceduralTexture.render();
  27202. }
  27203. }
  27204. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27205. }
  27206. // Clear
  27207. if (this.autoClearDepthAndStencil || this.autoClear) {
  27208. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27209. }
  27210. // Shadows
  27211. if (this.shadowsEnabled) {
  27212. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27213. var light = this.lights[lightIndex];
  27214. var shadowGenerator = light.getShadowGenerator();
  27215. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27216. var shadowMap = (shadowGenerator.getShadowMap());
  27217. if (this.textures.indexOf(shadowMap) !== -1) {
  27218. this._renderTargets.push(shadowMap);
  27219. }
  27220. }
  27221. }
  27222. }
  27223. // Depth renderer
  27224. for (var key in this._depthRenderer) {
  27225. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27226. }
  27227. // Geometry renderer
  27228. if (this._geometryBufferRenderer) {
  27229. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27230. }
  27231. // RenderPipeline
  27232. if (this._postProcessRenderPipelineManager) {
  27233. this._postProcessRenderPipelineManager.update();
  27234. }
  27235. // Multi-cameras?
  27236. if (this.activeCameras.length > 0) {
  27237. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27238. if (cameraIndex > 0) {
  27239. this._engine.clear(null, false, true, true);
  27240. }
  27241. this._processSubCameras(this.activeCameras[cameraIndex]);
  27242. }
  27243. }
  27244. else {
  27245. if (!this.activeCamera) {
  27246. throw new Error("No camera defined");
  27247. }
  27248. this._processSubCameras(this.activeCamera);
  27249. }
  27250. // Intersection checks
  27251. this._checkIntersections();
  27252. // Update the audio listener attached to the camera
  27253. if (BABYLON.AudioEngine) {
  27254. this._updateAudioParameters();
  27255. }
  27256. // After render
  27257. if (this.afterRender) {
  27258. this.afterRender();
  27259. }
  27260. this.onAfterRenderObservable.notifyObservers(this);
  27261. // Cleaning
  27262. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27263. var data = this._toBeDisposed.data[index];
  27264. if (data) {
  27265. data.dispose();
  27266. }
  27267. this._toBeDisposed[index] = null;
  27268. }
  27269. this._toBeDisposed.reset();
  27270. if (this.dumpNextRenderTargets) {
  27271. this.dumpNextRenderTargets = false;
  27272. }
  27273. this._activeBones.addCount(0, true);
  27274. this._activeIndices.addCount(0, true);
  27275. this._activeParticles.addCount(0, true);
  27276. };
  27277. Scene.prototype._updateAudioParameters = function () {
  27278. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27279. return;
  27280. }
  27281. var listeningCamera;
  27282. var audioEngine = BABYLON.Engine.audioEngine;
  27283. if (this.activeCameras.length > 0) {
  27284. listeningCamera = this.activeCameras[0];
  27285. }
  27286. else {
  27287. listeningCamera = this.activeCamera;
  27288. }
  27289. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27290. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27291. // for VR cameras
  27292. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27293. listeningCamera = listeningCamera.rigCameras[0];
  27294. }
  27295. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27296. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27297. cameraDirection.normalize();
  27298. // To avoid some errors on GearVR
  27299. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27300. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27301. }
  27302. var i;
  27303. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27304. var sound = this.mainSoundTrack.soundCollection[i];
  27305. if (sound.useCustomAttenuation) {
  27306. sound.updateDistanceFromListener();
  27307. }
  27308. }
  27309. for (i = 0; i < this.soundTracks.length; i++) {
  27310. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27311. sound = this.soundTracks[i].soundCollection[j];
  27312. if (sound.useCustomAttenuation) {
  27313. sound.updateDistanceFromListener();
  27314. }
  27315. }
  27316. }
  27317. }
  27318. };
  27319. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27320. // Audio
  27321. /**
  27322. * Gets or sets if audio support is enabled
  27323. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27324. */
  27325. get: function () {
  27326. return this._audioEnabled;
  27327. },
  27328. set: function (value) {
  27329. this._audioEnabled = value;
  27330. if (BABYLON.AudioEngine) {
  27331. if (this._audioEnabled) {
  27332. this._enableAudio();
  27333. }
  27334. else {
  27335. this._disableAudio();
  27336. }
  27337. }
  27338. },
  27339. enumerable: true,
  27340. configurable: true
  27341. });
  27342. Scene.prototype._disableAudio = function () {
  27343. var i;
  27344. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27345. this.mainSoundTrack.soundCollection[i].pause();
  27346. }
  27347. for (i = 0; i < this.soundTracks.length; i++) {
  27348. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27349. this.soundTracks[i].soundCollection[j].pause();
  27350. }
  27351. }
  27352. };
  27353. Scene.prototype._enableAudio = function () {
  27354. var i;
  27355. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27356. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27357. this.mainSoundTrack.soundCollection[i].play();
  27358. }
  27359. }
  27360. for (i = 0; i < this.soundTracks.length; i++) {
  27361. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27362. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27363. this.soundTracks[i].soundCollection[j].play();
  27364. }
  27365. }
  27366. }
  27367. };
  27368. Object.defineProperty(Scene.prototype, "headphone", {
  27369. /**
  27370. * Gets or sets if audio will be output to headphones
  27371. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27372. */
  27373. get: function () {
  27374. return this._headphone;
  27375. },
  27376. set: function (value) {
  27377. this._headphone = value;
  27378. if (BABYLON.AudioEngine) {
  27379. if (this._headphone) {
  27380. this._switchAudioModeForHeadphones();
  27381. }
  27382. else {
  27383. this._switchAudioModeForNormalSpeakers();
  27384. }
  27385. }
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. Scene.prototype._switchAudioModeForHeadphones = function () {
  27391. this.mainSoundTrack.switchPanningModelToHRTF();
  27392. for (var i = 0; i < this.soundTracks.length; i++) {
  27393. this.soundTracks[i].switchPanningModelToHRTF();
  27394. }
  27395. };
  27396. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27397. this.mainSoundTrack.switchPanningModelToEqualPower();
  27398. for (var i = 0; i < this.soundTracks.length; i++) {
  27399. this.soundTracks[i].switchPanningModelToEqualPower();
  27400. }
  27401. };
  27402. /**
  27403. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27404. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27405. * @returns the created depth renderer
  27406. */
  27407. Scene.prototype.enableDepthRenderer = function (camera) {
  27408. camera = camera || this.activeCamera;
  27409. if (!camera) {
  27410. throw "No camera available to enable depth renderer";
  27411. }
  27412. if (!this._depthRenderer[camera.id]) {
  27413. var textureType = 0;
  27414. if (this._engine.getCaps().textureHalfFloatRender) {
  27415. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27416. }
  27417. else if (this._engine.getCaps().textureFloatRender) {
  27418. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27419. }
  27420. else {
  27421. throw "Depth renderer does not support int texture type";
  27422. }
  27423. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27424. }
  27425. return this._depthRenderer[camera.id];
  27426. };
  27427. /**
  27428. * Disables a depth renderer for a given camera
  27429. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27430. */
  27431. Scene.prototype.disableDepthRenderer = function (camera) {
  27432. camera = camera || this.activeCamera;
  27433. if (!camera || !this._depthRenderer[camera.id]) {
  27434. return;
  27435. }
  27436. this._depthRenderer[camera.id].dispose();
  27437. delete this._depthRenderer[camera.id];
  27438. };
  27439. /**
  27440. * Enables a GeometryBufferRender and associates it with the scene
  27441. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27442. * @returns the GeometryBufferRenderer
  27443. */
  27444. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27445. if (ratio === void 0) { ratio = 1; }
  27446. if (this._geometryBufferRenderer) {
  27447. return this._geometryBufferRenderer;
  27448. }
  27449. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27450. if (!this._geometryBufferRenderer.isSupported) {
  27451. this._geometryBufferRenderer = null;
  27452. }
  27453. return this._geometryBufferRenderer;
  27454. };
  27455. /**
  27456. * Disables the GeometryBufferRender associated with the scene
  27457. */
  27458. Scene.prototype.disableGeometryBufferRenderer = function () {
  27459. if (!this._geometryBufferRenderer) {
  27460. return;
  27461. }
  27462. this._geometryBufferRenderer.dispose();
  27463. this._geometryBufferRenderer = null;
  27464. };
  27465. /**
  27466. * Freeze all materials
  27467. * A frozen material will not be updatable but should be faster to render
  27468. */
  27469. Scene.prototype.freezeMaterials = function () {
  27470. for (var i = 0; i < this.materials.length; i++) {
  27471. this.materials[i].freeze();
  27472. }
  27473. };
  27474. /**
  27475. * Unfreeze all materials
  27476. * A frozen material will not be updatable but should be faster to render
  27477. */
  27478. Scene.prototype.unfreezeMaterials = function () {
  27479. for (var i = 0; i < this.materials.length; i++) {
  27480. this.materials[i].unfreeze();
  27481. }
  27482. };
  27483. /**
  27484. * Releases all held ressources
  27485. */
  27486. Scene.prototype.dispose = function () {
  27487. this.beforeRender = null;
  27488. this.afterRender = null;
  27489. this.skeletons = [];
  27490. this.morphTargetManagers = [];
  27491. this.importedMeshesFiles = new Array();
  27492. this.stopAllAnimations();
  27493. this.resetCachedMaterial();
  27494. for (var key in this._depthRenderer) {
  27495. this._depthRenderer[key].dispose();
  27496. }
  27497. if (this._gamepadManager) {
  27498. this._gamepadManager.dispose();
  27499. this._gamepadManager = null;
  27500. }
  27501. // Smart arrays
  27502. if (this.activeCamera) {
  27503. this.activeCamera._activeMeshes.dispose();
  27504. this.activeCamera = null;
  27505. }
  27506. this._activeMeshes.dispose();
  27507. this._renderingManager.dispose();
  27508. this._processedMaterials.dispose();
  27509. this._activeParticleSystems.dispose();
  27510. this._activeSkeletons.dispose();
  27511. this._softwareSkinnedMeshes.dispose();
  27512. this._renderTargets.dispose();
  27513. this._registeredForLateAnimationBindings.dispose();
  27514. if (this._boundingBoxRenderer) {
  27515. this._boundingBoxRenderer.dispose();
  27516. }
  27517. this._meshesForIntersections.dispose();
  27518. this._toBeDisposed.dispose();
  27519. // Abort active requests
  27520. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27521. var request = _a[_i];
  27522. request.abort();
  27523. }
  27524. // Debug layer
  27525. if (this._debugLayer) {
  27526. this._debugLayer.hide();
  27527. }
  27528. // Events
  27529. this.onDisposeObservable.notifyObservers(this);
  27530. this.onDisposeObservable.clear();
  27531. this.onBeforeRenderObservable.clear();
  27532. this.onAfterRenderObservable.clear();
  27533. this.onBeforeRenderTargetsRenderObservable.clear();
  27534. this.onAfterRenderTargetsRenderObservable.clear();
  27535. this.onAfterStepObservable.clear();
  27536. this.onBeforeStepObservable.clear();
  27537. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27538. this.onAfterActiveMeshesEvaluationObservable.clear();
  27539. this.onBeforeParticlesRenderingObservable.clear();
  27540. this.onAfterParticlesRenderingObservable.clear();
  27541. this.onBeforeSpritesRenderingObservable.clear();
  27542. this.onAfterSpritesRenderingObservable.clear();
  27543. this.onBeforeDrawPhaseObservable.clear();
  27544. this.onAfterDrawPhaseObservable.clear();
  27545. this.onBeforePhysicsObservable.clear();
  27546. this.onAfterPhysicsObservable.clear();
  27547. this.onBeforeAnimationsObservable.clear();
  27548. this.onAfterAnimationsObservable.clear();
  27549. this.onDataLoadedObservable.clear();
  27550. this.detachControl();
  27551. // Release sounds & sounds tracks
  27552. if (BABYLON.AudioEngine) {
  27553. this.disposeSounds();
  27554. }
  27555. // VR Helper
  27556. if (this.VRHelper) {
  27557. this.VRHelper.dispose();
  27558. }
  27559. // Detach cameras
  27560. var canvas = this._engine.getRenderingCanvas();
  27561. if (canvas) {
  27562. var index;
  27563. for (index = 0; index < this.cameras.length; index++) {
  27564. this.cameras[index].detachControl(canvas);
  27565. }
  27566. }
  27567. // Release animation groups
  27568. while (this.animationGroups.length) {
  27569. this.animationGroups[0].dispose();
  27570. }
  27571. // Release lights
  27572. while (this.lights.length) {
  27573. this.lights[0].dispose();
  27574. }
  27575. // Release meshes
  27576. while (this.meshes.length) {
  27577. this.meshes[0].dispose(true);
  27578. }
  27579. while (this.transformNodes.length) {
  27580. this.removeTransformNode(this.transformNodes[0]);
  27581. }
  27582. // Release cameras
  27583. while (this.cameras.length) {
  27584. this.cameras[0].dispose();
  27585. }
  27586. // Release materials
  27587. if (this.defaultMaterial) {
  27588. this.defaultMaterial.dispose();
  27589. }
  27590. while (this.multiMaterials.length) {
  27591. this.multiMaterials[0].dispose();
  27592. }
  27593. while (this.materials.length) {
  27594. this.materials[0].dispose();
  27595. }
  27596. // Release particles
  27597. while (this.particleSystems.length) {
  27598. this.particleSystems[0].dispose();
  27599. }
  27600. // Release sprites
  27601. while (this.spriteManagers.length) {
  27602. this.spriteManagers[0].dispose();
  27603. }
  27604. // Release postProcesses
  27605. while (this.postProcesses.length) {
  27606. this.postProcesses[0].dispose();
  27607. }
  27608. // Release layers
  27609. while (this.layers.length) {
  27610. this.layers[0].dispose();
  27611. }
  27612. while (this.effectLayers.length) {
  27613. this.effectLayers[0].dispose();
  27614. }
  27615. // Release textures
  27616. while (this.textures.length) {
  27617. this.textures[0].dispose();
  27618. }
  27619. // Release UBO
  27620. this._sceneUbo.dispose();
  27621. if (this._alternateSceneUbo) {
  27622. this._alternateSceneUbo.dispose();
  27623. }
  27624. // Post-processes
  27625. this.postProcessManager.dispose();
  27626. if (this._postProcessRenderPipelineManager) {
  27627. this._postProcessRenderPipelineManager.dispose();
  27628. }
  27629. // Physics
  27630. if (this._physicsEngine) {
  27631. this.disablePhysicsEngine();
  27632. }
  27633. // Remove from engine
  27634. index = this._engine.scenes.indexOf(this);
  27635. if (index > -1) {
  27636. this._engine.scenes.splice(index, 1);
  27637. }
  27638. this._engine.wipeCaches(true);
  27639. this._isDisposed = true;
  27640. };
  27641. Object.defineProperty(Scene.prototype, "isDisposed", {
  27642. /**
  27643. * Gets if the scene is already disposed
  27644. */
  27645. get: function () {
  27646. return this._isDisposed;
  27647. },
  27648. enumerable: true,
  27649. configurable: true
  27650. });
  27651. /**
  27652. * Releases sounds & soundtracks
  27653. */
  27654. Scene.prototype.disposeSounds = function () {
  27655. if (!this._mainSoundTrack) {
  27656. return;
  27657. }
  27658. this.mainSoundTrack.dispose();
  27659. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27660. this.soundTracks[scIndex].dispose();
  27661. }
  27662. };
  27663. // Octrees
  27664. /**
  27665. * Get the world extend vectors with an optional filter
  27666. *
  27667. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27668. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27669. */
  27670. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27671. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27672. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27673. filterPredicate = filterPredicate || (function () { return true; });
  27674. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27675. mesh.computeWorldMatrix(true);
  27676. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27677. return;
  27678. }
  27679. var boundingInfo = mesh.getBoundingInfo();
  27680. var minBox = boundingInfo.boundingBox.minimumWorld;
  27681. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27682. BABYLON.Tools.CheckExtends(minBox, min, max);
  27683. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27684. });
  27685. return {
  27686. min: min,
  27687. max: max
  27688. };
  27689. };
  27690. /**
  27691. * Creates or updates the octree used to boost selection (picking)
  27692. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27693. * @param maxCapacity defines the maximum capacity per leaf
  27694. * @param maxDepth defines the maximum depth of the octree
  27695. * @returns an octree of AbstractMesh
  27696. */
  27697. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27698. if (maxCapacity === void 0) { maxCapacity = 64; }
  27699. if (maxDepth === void 0) { maxDepth = 2; }
  27700. if (!this._selectionOctree) {
  27701. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27702. }
  27703. var worldExtends = this.getWorldExtends();
  27704. // Update octree
  27705. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27706. return this._selectionOctree;
  27707. };
  27708. // Picking
  27709. /**
  27710. * Creates a ray that can be used to pick in the scene
  27711. * @param x defines the x coordinate of the origin (on-screen)
  27712. * @param y defines the y coordinate of the origin (on-screen)
  27713. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27714. * @param camera defines the camera to use for the picking
  27715. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27716. * @returns a Ray
  27717. */
  27718. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27719. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27720. var result = BABYLON.Ray.Zero();
  27721. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27722. return result;
  27723. };
  27724. /**
  27725. * Creates a ray that can be used to pick in the scene
  27726. * @param x defines the x coordinate of the origin (on-screen)
  27727. * @param y defines the y coordinate of the origin (on-screen)
  27728. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27729. * @param result defines the ray where to store the picking ray
  27730. * @param camera defines the camera to use for the picking
  27731. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27732. * @returns the current scene
  27733. */
  27734. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27735. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27736. var engine = this._engine;
  27737. if (!camera) {
  27738. if (!this.activeCamera)
  27739. throw new Error("Active camera not set");
  27740. camera = this.activeCamera;
  27741. }
  27742. var cameraViewport = camera.viewport;
  27743. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27744. // Moving coordinates to local viewport world
  27745. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27746. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27747. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27748. return this;
  27749. };
  27750. /**
  27751. * Creates a ray that can be used to pick in the scene
  27752. * @param x defines the x coordinate of the origin (on-screen)
  27753. * @param y defines the y coordinate of the origin (on-screen)
  27754. * @param camera defines the camera to use for the picking
  27755. * @returns a Ray
  27756. */
  27757. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27758. var result = BABYLON.Ray.Zero();
  27759. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27760. return result;
  27761. };
  27762. /**
  27763. * Creates a ray that can be used to pick in the scene
  27764. * @param x defines the x coordinate of the origin (on-screen)
  27765. * @param y defines the y coordinate of the origin (on-screen)
  27766. * @param result defines the ray where to store the picking ray
  27767. * @param camera defines the camera to use for the picking
  27768. * @returns the current scene
  27769. */
  27770. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27771. if (!BABYLON.PickingInfo) {
  27772. return this;
  27773. }
  27774. var engine = this._engine;
  27775. if (!camera) {
  27776. if (!this.activeCamera)
  27777. throw new Error("Active camera not set");
  27778. camera = this.activeCamera;
  27779. }
  27780. var cameraViewport = camera.viewport;
  27781. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27782. var identity = BABYLON.Matrix.Identity();
  27783. // Moving coordinates to local viewport world
  27784. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27785. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27786. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27787. return this;
  27788. };
  27789. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27790. if (!BABYLON.PickingInfo) {
  27791. return null;
  27792. }
  27793. var pickingInfo = null;
  27794. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27795. var mesh = this.meshes[meshIndex];
  27796. if (predicate) {
  27797. if (!predicate(mesh)) {
  27798. continue;
  27799. }
  27800. }
  27801. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27802. continue;
  27803. }
  27804. var world = mesh.getWorldMatrix();
  27805. var ray = rayFunction(world);
  27806. var result = mesh.intersects(ray, fastCheck);
  27807. if (!result || !result.hit)
  27808. continue;
  27809. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27810. continue;
  27811. pickingInfo = result;
  27812. if (fastCheck) {
  27813. break;
  27814. }
  27815. }
  27816. return pickingInfo || new BABYLON.PickingInfo();
  27817. };
  27818. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27819. if (!BABYLON.PickingInfo) {
  27820. return null;
  27821. }
  27822. var pickingInfos = new Array();
  27823. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27824. var mesh = this.meshes[meshIndex];
  27825. if (predicate) {
  27826. if (!predicate(mesh)) {
  27827. continue;
  27828. }
  27829. }
  27830. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27831. continue;
  27832. }
  27833. var world = mesh.getWorldMatrix();
  27834. var ray = rayFunction(world);
  27835. var result = mesh.intersects(ray, false);
  27836. if (!result || !result.hit)
  27837. continue;
  27838. pickingInfos.push(result);
  27839. }
  27840. return pickingInfos;
  27841. };
  27842. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27843. if (!BABYLON.PickingInfo) {
  27844. return null;
  27845. }
  27846. var pickingInfo = null;
  27847. if (!camera) {
  27848. if (!this.activeCamera) {
  27849. return null;
  27850. }
  27851. camera = this.activeCamera;
  27852. }
  27853. if (this.spriteManagers.length > 0) {
  27854. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27855. var spriteManager = this.spriteManagers[spriteIndex];
  27856. if (!spriteManager.isPickable) {
  27857. continue;
  27858. }
  27859. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27860. if (!result || !result.hit)
  27861. continue;
  27862. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27863. continue;
  27864. pickingInfo = result;
  27865. if (fastCheck) {
  27866. break;
  27867. }
  27868. }
  27869. }
  27870. return pickingInfo || new BABYLON.PickingInfo();
  27871. };
  27872. /** Launch a ray to try to pick a mesh in the scene
  27873. * @param x position on screen
  27874. * @param y position on screen
  27875. * @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
  27876. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27877. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27878. * @returns a PickingInfo
  27879. */
  27880. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27881. var _this = this;
  27882. if (!BABYLON.PickingInfo) {
  27883. return null;
  27884. }
  27885. return this._internalPick(function (world) {
  27886. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27887. return _this._tempPickingRay;
  27888. }, predicate, fastCheck);
  27889. };
  27890. /** Launch a ray to try to pick a sprite in the scene
  27891. * @param x position on screen
  27892. * @param y position on screen
  27893. * @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
  27894. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27895. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27896. * @returns a PickingInfo
  27897. */
  27898. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27899. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27900. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27901. };
  27902. /** Use the given ray to pick a mesh in the scene
  27903. * @param ray The ray to use to pick meshes
  27904. * @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
  27905. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27906. * @returns a PickingInfo
  27907. */
  27908. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27909. var _this = this;
  27910. return this._internalPick(function (world) {
  27911. if (!_this._pickWithRayInverseMatrix) {
  27912. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27913. }
  27914. world.invertToRef(_this._pickWithRayInverseMatrix);
  27915. if (!_this._cachedRayForTransform) {
  27916. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27917. }
  27918. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27919. return _this._cachedRayForTransform;
  27920. }, predicate, fastCheck);
  27921. };
  27922. /**
  27923. * Launch a ray to try to pick a mesh in the scene
  27924. * @param x X position on screen
  27925. * @param y Y position on screen
  27926. * @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
  27927. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27928. * @returns an array of PickingInfo
  27929. */
  27930. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27931. var _this = this;
  27932. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27933. };
  27934. /**
  27935. * Launch a ray to try to pick a mesh in the scene
  27936. * @param ray Ray to use
  27937. * @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
  27938. * @returns an array of PickingInfo
  27939. */
  27940. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27941. var _this = this;
  27942. return this._internalMultiPick(function (world) {
  27943. if (!_this._pickWithRayInverseMatrix) {
  27944. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27945. }
  27946. world.invertToRef(_this._pickWithRayInverseMatrix);
  27947. if (!_this._cachedRayForTransform) {
  27948. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27949. }
  27950. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27951. return _this._cachedRayForTransform;
  27952. }, predicate);
  27953. };
  27954. /**
  27955. * Force the value of meshUnderPointer
  27956. * @param mesh defines the mesh to use
  27957. */
  27958. Scene.prototype.setPointerOverMesh = function (mesh) {
  27959. if (this._pointerOverMesh === mesh) {
  27960. return;
  27961. }
  27962. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27963. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27964. }
  27965. this._pointerOverMesh = mesh;
  27966. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27967. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27968. }
  27969. };
  27970. /**
  27971. * Gets the mesh under the pointer
  27972. * @returns a Mesh or null if no mesh is under the pointer
  27973. */
  27974. Scene.prototype.getPointerOverMesh = function () {
  27975. return this._pointerOverMesh;
  27976. };
  27977. /**
  27978. * Force the sprite under the pointer
  27979. * @param sprite defines the sprite to use
  27980. */
  27981. Scene.prototype.setPointerOverSprite = function (sprite) {
  27982. if (this._pointerOverSprite === sprite) {
  27983. return;
  27984. }
  27985. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27986. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27987. }
  27988. this._pointerOverSprite = sprite;
  27989. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27990. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27991. }
  27992. };
  27993. /**
  27994. * Gets the sprite under the pointer
  27995. * @returns a Sprite or null if no sprite is under the pointer
  27996. */
  27997. Scene.prototype.getPointerOverSprite = function () {
  27998. return this._pointerOverSprite;
  27999. };
  28000. // Physics
  28001. /**
  28002. * Gets the current physics engine
  28003. * @returns a PhysicsEngine or null if none attached
  28004. */
  28005. Scene.prototype.getPhysicsEngine = function () {
  28006. return this._physicsEngine;
  28007. };
  28008. /**
  28009. * Enables physics to the current scene
  28010. * @param gravity defines the scene's gravity for the physics engine
  28011. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28012. * @return a boolean indicating if the physics engine was initialized
  28013. */
  28014. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28015. if (gravity === void 0) { gravity = null; }
  28016. if (this._physicsEngine) {
  28017. return true;
  28018. }
  28019. try {
  28020. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28021. return true;
  28022. }
  28023. catch (e) {
  28024. BABYLON.Tools.Error(e.message);
  28025. return false;
  28026. }
  28027. };
  28028. /**
  28029. * Disables and disposes the physics engine associated with the scene
  28030. */
  28031. Scene.prototype.disablePhysicsEngine = function () {
  28032. if (!this._physicsEngine) {
  28033. return;
  28034. }
  28035. this._physicsEngine.dispose();
  28036. this._physicsEngine = null;
  28037. };
  28038. /**
  28039. * Gets a boolean indicating if there is an active physics engine
  28040. * @returns a boolean indicating if there is an active physics engine
  28041. */
  28042. Scene.prototype.isPhysicsEnabled = function () {
  28043. return this._physicsEngine !== undefined;
  28044. };
  28045. /**
  28046. * Deletes a physics compound impostor
  28047. * @param compound defines the compound to delete
  28048. */
  28049. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28050. var mesh = compound.parts[0].mesh;
  28051. if (mesh.physicsImpostor) {
  28052. mesh.physicsImpostor.dispose( /*true*/);
  28053. mesh.physicsImpostor = null;
  28054. }
  28055. };
  28056. // Misc.
  28057. /** @ignore */
  28058. Scene.prototype._rebuildGeometries = function () {
  28059. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28060. var geometry = _a[_i];
  28061. geometry._rebuild();
  28062. }
  28063. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28064. var mesh = _c[_b];
  28065. mesh._rebuild();
  28066. }
  28067. if (this.postProcessManager) {
  28068. this.postProcessManager._rebuild();
  28069. }
  28070. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28071. var layer = _e[_d];
  28072. layer._rebuild();
  28073. }
  28074. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28075. var effectLayer = _g[_f];
  28076. effectLayer._rebuild();
  28077. }
  28078. if (this._boundingBoxRenderer) {
  28079. this._boundingBoxRenderer._rebuild();
  28080. }
  28081. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28082. var system = _j[_h];
  28083. system.rebuild();
  28084. }
  28085. if (this._postProcessRenderPipelineManager) {
  28086. this._postProcessRenderPipelineManager._rebuild();
  28087. }
  28088. };
  28089. /** @ignore */
  28090. Scene.prototype._rebuildTextures = function () {
  28091. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28092. var texture = _a[_i];
  28093. texture._rebuild();
  28094. }
  28095. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28096. };
  28097. /**
  28098. * Creates a default light for the scene.
  28099. * @param replace Whether to replace the existing lights in the scene.
  28100. */
  28101. Scene.prototype.createDefaultLight = function (replace) {
  28102. if (replace === void 0) { replace = false; }
  28103. // Dispose existing light in replace mode.
  28104. if (replace) {
  28105. if (this.lights) {
  28106. for (var i = 0; i < this.lights.length; i++) {
  28107. this.lights[i].dispose();
  28108. }
  28109. }
  28110. }
  28111. // Light
  28112. if (this.lights.length === 0) {
  28113. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28114. }
  28115. };
  28116. /**
  28117. * Creates a default camera for the scene.
  28118. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28119. * @param replace Whether to replace the existing active camera in the scene.
  28120. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28121. */
  28122. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28123. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28124. if (replace === void 0) { replace = false; }
  28125. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28126. // Dispose existing camera in replace mode.
  28127. if (replace) {
  28128. if (this.activeCamera) {
  28129. this.activeCamera.dispose();
  28130. this.activeCamera = null;
  28131. }
  28132. }
  28133. // Camera
  28134. if (!this.activeCamera) {
  28135. var worldExtends = this.getWorldExtends();
  28136. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28137. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28138. var camera;
  28139. var radius = worldSize.length() * 1.5;
  28140. // empty scene scenario!
  28141. if (!isFinite(radius)) {
  28142. radius = 1;
  28143. worldCenter.copyFromFloats(0, 0, 0);
  28144. }
  28145. if (createArcRotateCamera) {
  28146. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28147. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28148. arcRotateCamera.wheelPrecision = 100 / radius;
  28149. camera = arcRotateCamera;
  28150. }
  28151. else {
  28152. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28153. freeCamera.setTarget(worldCenter);
  28154. camera = freeCamera;
  28155. }
  28156. camera.minZ = radius * 0.01;
  28157. camera.maxZ = radius * 1000;
  28158. camera.speed = radius * 0.2;
  28159. this.activeCamera = camera;
  28160. var canvas = this.getEngine().getRenderingCanvas();
  28161. if (attachCameraControls && canvas) {
  28162. camera.attachControl(canvas);
  28163. }
  28164. }
  28165. };
  28166. /**
  28167. * Creates a default camera and a default light
  28168. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28169. * @param replace defines if the camera and/or light will replace the existing ones
  28170. * @param attachCameraControls defines if attachControl will be called on the new camera
  28171. */
  28172. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28173. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28174. if (replace === void 0) { replace = false; }
  28175. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28176. this.createDefaultLight(replace);
  28177. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28178. };
  28179. /**
  28180. * Creates a new sky box
  28181. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28182. * @param environmentTexture defines the texture to use as environment texture
  28183. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28184. * @param scale defines the overall scale of the skybox
  28185. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28186. * @returns a new mesh holding the sky box
  28187. */
  28188. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28189. if (pbr === void 0) { pbr = false; }
  28190. if (scale === void 0) { scale = 1000; }
  28191. if (blur === void 0) { blur = 0; }
  28192. if (environmentTexture) {
  28193. this.environmentTexture = environmentTexture;
  28194. }
  28195. if (!this.environmentTexture) {
  28196. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28197. return null;
  28198. }
  28199. // Skybox
  28200. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28201. if (pbr) {
  28202. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28203. hdrSkyboxMaterial.backFaceCulling = false;
  28204. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28205. if (hdrSkyboxMaterial.reflectionTexture) {
  28206. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28207. }
  28208. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28209. hdrSkyboxMaterial.disableLighting = true;
  28210. hdrSkyboxMaterial.twoSidedLighting = true;
  28211. hdrSkybox.infiniteDistance = true;
  28212. hdrSkybox.material = hdrSkyboxMaterial;
  28213. }
  28214. else {
  28215. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28216. skyboxMaterial.backFaceCulling = false;
  28217. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28218. if (skyboxMaterial.reflectionTexture) {
  28219. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28220. }
  28221. skyboxMaterial.disableLighting = true;
  28222. hdrSkybox.infiniteDistance = true;
  28223. hdrSkybox.material = skyboxMaterial;
  28224. }
  28225. return hdrSkybox;
  28226. };
  28227. /**
  28228. * Creates a new environment
  28229. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28230. * @param options defines the options you can use to configure the environment
  28231. * @returns the new EnvironmentHelper
  28232. */
  28233. Scene.prototype.createDefaultEnvironment = function (options) {
  28234. if (BABYLON.EnvironmentHelper) {
  28235. return new BABYLON.EnvironmentHelper(options, this);
  28236. }
  28237. return null;
  28238. };
  28239. /**
  28240. * Creates a new VREXperienceHelper
  28241. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28242. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28243. * @returns a new VREXperienceHelper
  28244. */
  28245. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28246. if (webVROptions === void 0) { webVROptions = {}; }
  28247. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28248. };
  28249. // Tags
  28250. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28251. if (tagsQuery === undefined) {
  28252. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28253. return list;
  28254. }
  28255. var listByTags = [];
  28256. forEach = forEach || (function (item) { return; });
  28257. for (var i in list) {
  28258. var item = list[i];
  28259. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28260. listByTags.push(item);
  28261. forEach(item);
  28262. }
  28263. }
  28264. return listByTags;
  28265. };
  28266. /**
  28267. * Get a list of meshes by tags
  28268. * @param tagsQuery defines the tags query to use
  28269. * @param forEach defines a predicate used to filter results
  28270. * @returns an array of Mesh
  28271. */
  28272. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28273. return this._getByTags(this.meshes, tagsQuery, forEach);
  28274. };
  28275. /**
  28276. * Get a list of cameras by tags
  28277. * @param tagsQuery defines the tags query to use
  28278. * @param forEach defines a predicate used to filter results
  28279. * @returns an array of Camera
  28280. */
  28281. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28282. return this._getByTags(this.cameras, tagsQuery, forEach);
  28283. };
  28284. /**
  28285. * Get a list of lights by tags
  28286. * @param tagsQuery defines the tags query to use
  28287. * @param forEach defines a predicate used to filter results
  28288. * @returns an array of Light
  28289. */
  28290. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28291. return this._getByTags(this.lights, tagsQuery, forEach);
  28292. };
  28293. /**
  28294. * Get a list of materials by tags
  28295. * @param tagsQuery defines the tags query to use
  28296. * @param forEach defines a predicate used to filter results
  28297. * @returns an array of Material
  28298. */
  28299. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28300. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28301. };
  28302. /**
  28303. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28304. * This allowed control for front to back rendering or reversly depending of the special needs.
  28305. *
  28306. * @param renderingGroupId The rendering group id corresponding to its index
  28307. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28308. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28309. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28310. */
  28311. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28312. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28313. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28314. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28315. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28316. };
  28317. /**
  28318. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28319. *
  28320. * @param renderingGroupId The rendering group id corresponding to its index
  28321. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28322. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28323. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28324. */
  28325. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28326. if (depth === void 0) { depth = true; }
  28327. if (stencil === void 0) { stencil = true; }
  28328. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28329. };
  28330. /**
  28331. * Will flag all materials as dirty to trigger new shader compilation
  28332. * @param flag defines the flag used to specify which material part must be marked as dirty
  28333. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28334. */
  28335. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28336. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28337. var material = _a[_i];
  28338. if (predicate && !predicate(material)) {
  28339. continue;
  28340. }
  28341. material.markAsDirty(flag);
  28342. }
  28343. };
  28344. /** @ignore */
  28345. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28346. var _this = this;
  28347. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28348. this._activeRequests.push(request);
  28349. request.onCompleteObservable.add(function (request) {
  28350. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28351. });
  28352. return request;
  28353. };
  28354. /** @ignore */
  28355. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28356. var _this = this;
  28357. return new Promise(function (resolve, reject) {
  28358. _this._loadFile(url, function (data) {
  28359. resolve(data);
  28360. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28361. reject(exception);
  28362. });
  28363. });
  28364. };
  28365. // Statics
  28366. Scene._FOGMODE_NONE = 0;
  28367. Scene._FOGMODE_EXP = 1;
  28368. Scene._FOGMODE_EXP2 = 2;
  28369. Scene._FOGMODE_LINEAR = 3;
  28370. Scene._uniqueIdCounter = 0;
  28371. /**
  28372. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28373. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28374. */
  28375. Scene.MinDeltaTime = 1.0;
  28376. /**
  28377. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28378. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28379. */
  28380. Scene.MaxDeltaTime = 1000.0;
  28381. /** The distance in pixel that you have to move to prevent some events */
  28382. Scene.DragMovementThreshold = 10; // in pixels
  28383. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28384. Scene.LongPressDelay = 500; // in milliseconds
  28385. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28386. Scene.DoubleClickDelay = 300; // in milliseconds
  28387. /** If you need to check double click without raising a single click at first click, enable this flag */
  28388. Scene.ExclusiveDoubleClickMode = false;
  28389. return Scene;
  28390. }());
  28391. BABYLON.Scene = Scene;
  28392. })(BABYLON || (BABYLON = {}));
  28393. //# sourceMappingURL=babylon.scene.js.map
  28394. var BABYLON;
  28395. (function (BABYLON) {
  28396. /**
  28397. * Set of assets to keep when moving a scene into an asset container.
  28398. */
  28399. var KeepAssets = /** @class */ (function () {
  28400. function KeepAssets() {
  28401. /**
  28402. * Cameras to keep.
  28403. */
  28404. this.cameras = new Array();
  28405. /**
  28406. * Lights to keep.
  28407. */
  28408. this.lights = new Array();
  28409. /**
  28410. * Meshes to keep.
  28411. */
  28412. this.meshes = new Array();
  28413. /**
  28414. * Skeletons to keep.
  28415. */
  28416. this.skeletons = new Array();
  28417. /**
  28418. * ParticleSystems to keep.
  28419. */
  28420. this.particleSystems = new Array();
  28421. /**
  28422. * Animations to keep.
  28423. */
  28424. this.animations = new Array();
  28425. /**
  28426. * AnimationGroups to keep.
  28427. */
  28428. this.animationGroups = new Array();
  28429. /**
  28430. * MultiMaterials to keep.
  28431. */
  28432. this.multiMaterials = new Array();
  28433. /**
  28434. * Materials to keep.
  28435. */
  28436. this.materials = new Array();
  28437. /**
  28438. * MorphTargetManagers to keep.
  28439. */
  28440. this.morphTargetManagers = new Array();
  28441. /**
  28442. * Geometries to keep.
  28443. */
  28444. this.geometries = new Array();
  28445. /**
  28446. * TransformNodes to keep.
  28447. */
  28448. this.transformNodes = new Array();
  28449. /**
  28450. * LensFlareSystems to keep.
  28451. */
  28452. this.lensFlareSystems = new Array();
  28453. /**
  28454. * ShadowGenerators to keep.
  28455. */
  28456. this.shadowGenerators = new Array();
  28457. /**
  28458. * ActionManagers to keep.
  28459. */
  28460. this.actionManagers = new Array();
  28461. /**
  28462. * Sounds to keep.
  28463. */
  28464. this.sounds = new Array();
  28465. /**
  28466. * Textures to keep.
  28467. */
  28468. this.textures = new Array();
  28469. /**
  28470. * Effect layers to keep.
  28471. */
  28472. this.effectLayers = new Array();
  28473. }
  28474. return KeepAssets;
  28475. }());
  28476. BABYLON.KeepAssets = KeepAssets;
  28477. /**
  28478. * Container with a set of assets that can be added or removed from a scene.
  28479. */
  28480. var AssetContainer = /** @class */ (function () {
  28481. /**
  28482. * Instantiates an AssetContainer.
  28483. * @param scene The scene the AssetContainer belongs to.
  28484. */
  28485. function AssetContainer(scene) {
  28486. // Objects
  28487. /**
  28488. * Cameras populated in the container.
  28489. */
  28490. this.cameras = new Array();
  28491. /**
  28492. * Lights populated in the container.
  28493. */
  28494. this.lights = new Array();
  28495. /**
  28496. * Meshes populated in the container.
  28497. */
  28498. this.meshes = new Array();
  28499. /**
  28500. * Skeletons populated in the container.
  28501. */
  28502. this.skeletons = new Array();
  28503. /**
  28504. * ParticleSystems populated in the container.
  28505. */
  28506. this.particleSystems = new Array();
  28507. /**
  28508. * Animations populated in the container.
  28509. */
  28510. this.animations = new Array();
  28511. /**
  28512. * AnimationGroups populated in the container.
  28513. */
  28514. this.animationGroups = new Array();
  28515. /**
  28516. * MultiMaterials populated in the container.
  28517. */
  28518. this.multiMaterials = new Array();
  28519. /**
  28520. * Materials populated in the container.
  28521. */
  28522. this.materials = new Array();
  28523. /**
  28524. * MorphTargetManagers populated in the container.
  28525. */
  28526. this.morphTargetManagers = new Array();
  28527. /**
  28528. * Geometries populated in the container.
  28529. */
  28530. this.geometries = new Array();
  28531. /**
  28532. * TransformNodes populated in the container.
  28533. */
  28534. this.transformNodes = new Array();
  28535. /**
  28536. * LensFlareSystems populated in the container.
  28537. */
  28538. this.lensFlareSystems = new Array();
  28539. /**
  28540. * ShadowGenerators populated in the container.
  28541. */
  28542. this.shadowGenerators = new Array();
  28543. /**
  28544. * ActionManagers populated in the container.
  28545. */
  28546. this.actionManagers = new Array();
  28547. /**
  28548. * Sounds populated in the container.
  28549. */
  28550. this.sounds = new Array();
  28551. /**
  28552. * Textures populated in the container.
  28553. */
  28554. this.textures = new Array();
  28555. /**
  28556. * Effect layers populated in the container.
  28557. */
  28558. this.effectLayers = new Array();
  28559. this.scene = scene;
  28560. }
  28561. /**
  28562. * Adds all the assets from the container to the scene.
  28563. */
  28564. AssetContainer.prototype.addAllToScene = function () {
  28565. var _this = this;
  28566. this.cameras.forEach(function (o) {
  28567. _this.scene.addCamera(o);
  28568. });
  28569. this.lights.forEach(function (o) {
  28570. _this.scene.addLight(o);
  28571. });
  28572. this.meshes.forEach(function (o) {
  28573. _this.scene.addMesh(o);
  28574. });
  28575. this.skeletons.forEach(function (o) {
  28576. _this.scene.addSkeleton(o);
  28577. });
  28578. this.particleSystems.forEach(function (o) {
  28579. _this.scene.addParticleSystem(o);
  28580. });
  28581. this.animations.forEach(function (o) {
  28582. _this.scene.addAnimation(o);
  28583. });
  28584. this.animationGroups.forEach(function (o) {
  28585. _this.scene.addAnimationGroup(o);
  28586. });
  28587. this.multiMaterials.forEach(function (o) {
  28588. _this.scene.addMultiMaterial(o);
  28589. });
  28590. this.materials.forEach(function (o) {
  28591. _this.scene.addMaterial(o);
  28592. });
  28593. this.morphTargetManagers.forEach(function (o) {
  28594. _this.scene.addMorphTargetManager(o);
  28595. });
  28596. this.geometries.forEach(function (o) {
  28597. _this.scene.addGeometry(o);
  28598. });
  28599. this.transformNodes.forEach(function (o) {
  28600. _this.scene.addTransformNode(o);
  28601. });
  28602. this.lensFlareSystems.forEach(function (o) {
  28603. _this.scene.addLensFlareSystem(o);
  28604. });
  28605. this.actionManagers.forEach(function (o) {
  28606. _this.scene.addActionManager(o);
  28607. });
  28608. this.sounds.forEach(function (o) {
  28609. o.play();
  28610. o.autoplay = true;
  28611. _this.scene.mainSoundTrack.AddSound(o);
  28612. });
  28613. this.textures.forEach(function (o) {
  28614. _this.scene.addTexture(o);
  28615. });
  28616. this.effectLayers.forEach(function (o) {
  28617. _this.scene.addEffectLayer(o);
  28618. });
  28619. };
  28620. /**
  28621. * Removes all the assets in the container from the scene
  28622. */
  28623. AssetContainer.prototype.removeAllFromScene = function () {
  28624. var _this = this;
  28625. this.cameras.forEach(function (o) {
  28626. _this.scene.removeCamera(o);
  28627. });
  28628. this.lights.forEach(function (o) {
  28629. _this.scene.removeLight(o);
  28630. });
  28631. this.meshes.forEach(function (o) {
  28632. _this.scene.removeMesh(o);
  28633. });
  28634. this.skeletons.forEach(function (o) {
  28635. _this.scene.removeSkeleton(o);
  28636. });
  28637. this.particleSystems.forEach(function (o) {
  28638. _this.scene.removeParticleSystem(o);
  28639. });
  28640. this.animations.forEach(function (o) {
  28641. _this.scene.removeAnimation(o);
  28642. });
  28643. this.animationGroups.forEach(function (o) {
  28644. _this.scene.removeAnimationGroup(o);
  28645. });
  28646. this.multiMaterials.forEach(function (o) {
  28647. _this.scene.removeMultiMaterial(o);
  28648. });
  28649. this.materials.forEach(function (o) {
  28650. _this.scene.removeMaterial(o);
  28651. });
  28652. this.morphTargetManagers.forEach(function (o) {
  28653. _this.scene.removeMorphTargetManager(o);
  28654. });
  28655. this.geometries.forEach(function (o) {
  28656. _this.scene.removeGeometry(o);
  28657. });
  28658. this.transformNodes.forEach(function (o) {
  28659. _this.scene.removeTransformNode(o);
  28660. });
  28661. this.lensFlareSystems.forEach(function (o) {
  28662. _this.scene.removeLensFlareSystem(o);
  28663. });
  28664. this.actionManagers.forEach(function (o) {
  28665. _this.scene.removeActionManager(o);
  28666. });
  28667. this.sounds.forEach(function (o) {
  28668. o.stop();
  28669. o.autoplay = false;
  28670. _this.scene.mainSoundTrack.RemoveSound(o);
  28671. });
  28672. this.textures.forEach(function (o) {
  28673. _this.scene.removeTexture(o);
  28674. });
  28675. this.effectLayers.forEach(function (o) {
  28676. _this.scene.removeEffectLayer(o);
  28677. });
  28678. };
  28679. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28680. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28681. var asset = sourceAssets_1[_i];
  28682. var move = true;
  28683. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28684. var keepAsset = keepAssets_1[_a];
  28685. if (asset === keepAsset) {
  28686. move = false;
  28687. break;
  28688. }
  28689. }
  28690. if (move) {
  28691. targetAssets.push(asset);
  28692. }
  28693. }
  28694. };
  28695. /**
  28696. * Removes all the assets contained in the scene and adds them to the container.
  28697. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28698. */
  28699. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28700. if (keepAssets === undefined) {
  28701. keepAssets = new KeepAssets();
  28702. }
  28703. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28704. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28705. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28706. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28707. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28708. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28709. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28710. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28711. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28712. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28713. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28714. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28715. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28716. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28717. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28718. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28719. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28720. this.removeAllFromScene();
  28721. };
  28722. return AssetContainer;
  28723. }());
  28724. BABYLON.AssetContainer = AssetContainer;
  28725. })(BABYLON || (BABYLON = {}));
  28726. //# sourceMappingURL=babylon.assetContainer.js.map
  28727. var BABYLON;
  28728. (function (BABYLON) {
  28729. var Buffer = /** @class */ (function () {
  28730. /**
  28731. * Constructor
  28732. * @param engine the engine
  28733. * @param data the data to use for this buffer
  28734. * @param updatable whether the data is updatable
  28735. * @param stride the stride (optional)
  28736. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28737. * @param instanced whether the buffer is instanced (optional)
  28738. * @param useBytes set to true if the stride in in bytes (optional)
  28739. */
  28740. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28741. if (stride === void 0) { stride = 0; }
  28742. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28743. if (instanced === void 0) { instanced = false; }
  28744. if (useBytes === void 0) { useBytes = false; }
  28745. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28746. this._engine = engine.getScene().getEngine();
  28747. }
  28748. else {
  28749. this._engine = engine;
  28750. }
  28751. this._updatable = updatable;
  28752. this._instanced = instanced;
  28753. this._data = data;
  28754. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28755. if (!postponeInternalCreation) { // by default
  28756. this.create();
  28757. }
  28758. }
  28759. /**
  28760. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28761. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28762. * @param offset defines offset in the buffer (0 by default)
  28763. * @param size defines the size in floats of attributes (position is 3 for instance)
  28764. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28765. * @param instanced defines if the vertex buffer contains indexed data
  28766. * @param useBytes defines if the offset and stride are in bytes
  28767. * @returns the new vertex buffer
  28768. */
  28769. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28770. if (useBytes === void 0) { useBytes = false; }
  28771. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28772. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28773. // a lot of these parameters are ignored as they are overriden by the buffer
  28774. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28775. };
  28776. // Properties
  28777. Buffer.prototype.isUpdatable = function () {
  28778. return this._updatable;
  28779. };
  28780. Buffer.prototype.getData = function () {
  28781. return this._data;
  28782. };
  28783. Buffer.prototype.getBuffer = function () {
  28784. return this._buffer;
  28785. };
  28786. /**
  28787. * Gets the stride in float32 units (i.e. byte stride / 4).
  28788. * May not be an integer if the byte stride is not divisible by 4.
  28789. * DEPRECATED. Use byteStride instead.
  28790. * @returns the stride in float32 units
  28791. */
  28792. Buffer.prototype.getStrideSize = function () {
  28793. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28794. };
  28795. // Methods
  28796. Buffer.prototype.create = function (data) {
  28797. if (data === void 0) { data = null; }
  28798. if (!data && this._buffer) {
  28799. return; // nothing to do
  28800. }
  28801. data = data || this._data;
  28802. if (!data) {
  28803. return;
  28804. }
  28805. if (!this._buffer) { // create buffer
  28806. if (this._updatable) {
  28807. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28808. this._data = data;
  28809. }
  28810. else {
  28811. this._buffer = this._engine.createVertexBuffer(data);
  28812. }
  28813. }
  28814. else if (this._updatable) { // update buffer
  28815. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28816. this._data = data;
  28817. }
  28818. };
  28819. Buffer.prototype._rebuild = function () {
  28820. this._buffer = null;
  28821. this.create(this._data);
  28822. };
  28823. Buffer.prototype.update = function (data) {
  28824. this.create(data);
  28825. };
  28826. /**
  28827. * Updates the data directly.
  28828. * @param data the new data
  28829. * @param offset the new offset
  28830. * @param vertexCount the vertex count (optional)
  28831. * @param useBytes set to true if the offset is in bytes
  28832. */
  28833. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28834. if (useBytes === void 0) { useBytes = false; }
  28835. if (!this._buffer) {
  28836. return;
  28837. }
  28838. if (this._updatable) { // update buffer
  28839. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28840. this._data = null;
  28841. }
  28842. };
  28843. Buffer.prototype.dispose = function () {
  28844. if (!this._buffer) {
  28845. return;
  28846. }
  28847. if (this._engine._releaseBuffer(this._buffer)) {
  28848. this._buffer = null;
  28849. }
  28850. };
  28851. return Buffer;
  28852. }());
  28853. BABYLON.Buffer = Buffer;
  28854. })(BABYLON || (BABYLON = {}));
  28855. //# sourceMappingURL=babylon.buffer.js.map
  28856. var BABYLON;
  28857. (function (BABYLON) {
  28858. var VertexBuffer = /** @class */ (function () {
  28859. /**
  28860. * Constructor
  28861. * @param engine the engine
  28862. * @param data the data to use for this vertex buffer
  28863. * @param kind the vertex buffer kind
  28864. * @param updatable whether the data is updatable
  28865. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28866. * @param stride the stride (optional)
  28867. * @param instanced whether the buffer is instanced (optional)
  28868. * @param offset the offset of the data (optional)
  28869. * @param size the number of components (optional)
  28870. * @param type the type of the component (optional)
  28871. * @param normalized whether the data contains normalized data (optional)
  28872. * @param useBytes set to true if stride and offset are in bytes (optional)
  28873. */
  28874. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28875. if (normalized === void 0) { normalized = false; }
  28876. if (useBytes === void 0) { useBytes = false; }
  28877. if (data instanceof BABYLON.Buffer) {
  28878. this._buffer = data;
  28879. this._ownsBuffer = false;
  28880. }
  28881. else {
  28882. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28883. this._ownsBuffer = true;
  28884. }
  28885. this._kind = kind;
  28886. if (type == undefined) {
  28887. var data_1 = this.getData();
  28888. this.type = VertexBuffer.FLOAT;
  28889. if (data_1 instanceof Int8Array)
  28890. this.type = VertexBuffer.BYTE;
  28891. else if (data_1 instanceof Uint8Array)
  28892. this.type = VertexBuffer.UNSIGNED_BYTE;
  28893. else if (data_1 instanceof Int16Array)
  28894. this.type = VertexBuffer.SHORT;
  28895. else if (data_1 instanceof Uint16Array)
  28896. this.type = VertexBuffer.UNSIGNED_SHORT;
  28897. else if (data_1 instanceof Int32Array)
  28898. this.type = VertexBuffer.INT;
  28899. else if (data_1 instanceof Uint32Array)
  28900. this.type = VertexBuffer.UNSIGNED_INT;
  28901. }
  28902. else {
  28903. this.type = type;
  28904. }
  28905. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28906. if (useBytes) {
  28907. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28908. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28909. this.byteOffset = offset || 0;
  28910. }
  28911. else {
  28912. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28913. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28914. this.byteOffset = (offset || 0) * typeByteLength;
  28915. }
  28916. this.normalized = normalized;
  28917. this._instanced = instanced !== undefined ? instanced : false;
  28918. this._instanceDivisor = instanced ? 1 : 0;
  28919. }
  28920. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28921. /**
  28922. * Gets or sets the instance divisor when in instanced mode
  28923. */
  28924. get: function () {
  28925. return this._instanceDivisor;
  28926. },
  28927. set: function (value) {
  28928. this._instanceDivisor = value;
  28929. if (value == 0) {
  28930. this._instanced = false;
  28931. }
  28932. else {
  28933. this._instanced = true;
  28934. }
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. VertexBuffer.prototype._rebuild = function () {
  28940. if (!this._buffer) {
  28941. return;
  28942. }
  28943. this._buffer._rebuild();
  28944. };
  28945. /**
  28946. * Returns the kind of the VertexBuffer (string).
  28947. */
  28948. VertexBuffer.prototype.getKind = function () {
  28949. return this._kind;
  28950. };
  28951. // Properties
  28952. /**
  28953. * Boolean : is the VertexBuffer updatable ?
  28954. */
  28955. VertexBuffer.prototype.isUpdatable = function () {
  28956. return this._buffer.isUpdatable();
  28957. };
  28958. /**
  28959. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28960. */
  28961. VertexBuffer.prototype.getData = function () {
  28962. return this._buffer.getData();
  28963. };
  28964. /**
  28965. * Returns the WebGLBuffer associated to the VertexBuffer.
  28966. */
  28967. VertexBuffer.prototype.getBuffer = function () {
  28968. return this._buffer.getBuffer();
  28969. };
  28970. /**
  28971. * Returns the stride as a multiple of the type byte length.
  28972. * DEPRECATED. Use byteStride instead.
  28973. */
  28974. VertexBuffer.prototype.getStrideSize = function () {
  28975. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28976. };
  28977. /**
  28978. * Returns the offset as a multiple of the type byte length.
  28979. * DEPRECATED. Use byteOffset instead.
  28980. */
  28981. VertexBuffer.prototype.getOffset = function () {
  28982. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28983. };
  28984. /**
  28985. * Returns the number of components per vertex attribute (integer).
  28986. */
  28987. VertexBuffer.prototype.getSize = function () {
  28988. return this._size;
  28989. };
  28990. /**
  28991. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28992. */
  28993. VertexBuffer.prototype.getIsInstanced = function () {
  28994. return this._instanced;
  28995. };
  28996. /**
  28997. * Returns the instancing divisor, zero for non-instanced (integer).
  28998. */
  28999. VertexBuffer.prototype.getInstanceDivisor = function () {
  29000. return this._instanceDivisor;
  29001. };
  29002. // Methods
  29003. /**
  29004. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29005. * Returns the created WebGLBuffer.
  29006. */
  29007. VertexBuffer.prototype.create = function (data) {
  29008. return this._buffer.create(data);
  29009. };
  29010. /**
  29011. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29012. * This function will create a new buffer if the current one is not updatable
  29013. * Returns the updated WebGLBuffer.
  29014. */
  29015. VertexBuffer.prototype.update = function (data) {
  29016. return this._buffer.update(data);
  29017. };
  29018. /**
  29019. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29020. * Returns the directly updated WebGLBuffer.
  29021. * @param data the new data
  29022. * @param offset the new offset
  29023. * @param useBytes set to true if the offset is in bytes
  29024. */
  29025. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29026. if (useBytes === void 0) { useBytes = false; }
  29027. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29028. };
  29029. /**
  29030. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29031. */
  29032. VertexBuffer.prototype.dispose = function () {
  29033. if (this._ownsBuffer) {
  29034. this._buffer.dispose();
  29035. }
  29036. };
  29037. /**
  29038. * Enumerates each value of this vertex buffer as numbers.
  29039. * @param count the number of values to enumerate
  29040. * @param callback the callback function called for each value
  29041. */
  29042. VertexBuffer.prototype.forEach = function (count, callback) {
  29043. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29044. };
  29045. Object.defineProperty(VertexBuffer, "PositionKind", {
  29046. get: function () {
  29047. return VertexBuffer._PositionKind;
  29048. },
  29049. enumerable: true,
  29050. configurable: true
  29051. });
  29052. Object.defineProperty(VertexBuffer, "NormalKind", {
  29053. get: function () {
  29054. return VertexBuffer._NormalKind;
  29055. },
  29056. enumerable: true,
  29057. configurable: true
  29058. });
  29059. Object.defineProperty(VertexBuffer, "TangentKind", {
  29060. get: function () {
  29061. return VertexBuffer._TangentKind;
  29062. },
  29063. enumerable: true,
  29064. configurable: true
  29065. });
  29066. Object.defineProperty(VertexBuffer, "UVKind", {
  29067. get: function () {
  29068. return VertexBuffer._UVKind;
  29069. },
  29070. enumerable: true,
  29071. configurable: true
  29072. });
  29073. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29074. get: function () {
  29075. return VertexBuffer._UV2Kind;
  29076. },
  29077. enumerable: true,
  29078. configurable: true
  29079. });
  29080. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29081. get: function () {
  29082. return VertexBuffer._UV3Kind;
  29083. },
  29084. enumerable: true,
  29085. configurable: true
  29086. });
  29087. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29088. get: function () {
  29089. return VertexBuffer._UV4Kind;
  29090. },
  29091. enumerable: true,
  29092. configurable: true
  29093. });
  29094. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29095. get: function () {
  29096. return VertexBuffer._UV5Kind;
  29097. },
  29098. enumerable: true,
  29099. configurable: true
  29100. });
  29101. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29102. get: function () {
  29103. return VertexBuffer._UV6Kind;
  29104. },
  29105. enumerable: true,
  29106. configurable: true
  29107. });
  29108. Object.defineProperty(VertexBuffer, "ColorKind", {
  29109. get: function () {
  29110. return VertexBuffer._ColorKind;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29116. get: function () {
  29117. return VertexBuffer._MatricesIndicesKind;
  29118. },
  29119. enumerable: true,
  29120. configurable: true
  29121. });
  29122. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29123. get: function () {
  29124. return VertexBuffer._MatricesWeightsKind;
  29125. },
  29126. enumerable: true,
  29127. configurable: true
  29128. });
  29129. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29130. get: function () {
  29131. return VertexBuffer._MatricesIndicesExtraKind;
  29132. },
  29133. enumerable: true,
  29134. configurable: true
  29135. });
  29136. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29137. get: function () {
  29138. return VertexBuffer._MatricesWeightsExtraKind;
  29139. },
  29140. enumerable: true,
  29141. configurable: true
  29142. });
  29143. /**
  29144. * Deduces the stride given a kind.
  29145. * @param kind The kind string to deduce
  29146. * @returns The deduced stride
  29147. */
  29148. VertexBuffer.DeduceStride = function (kind) {
  29149. switch (kind) {
  29150. case VertexBuffer.UVKind:
  29151. case VertexBuffer.UV2Kind:
  29152. case VertexBuffer.UV3Kind:
  29153. case VertexBuffer.UV4Kind:
  29154. case VertexBuffer.UV5Kind:
  29155. case VertexBuffer.UV6Kind:
  29156. return 2;
  29157. case VertexBuffer.NormalKind:
  29158. case VertexBuffer.PositionKind:
  29159. return 3;
  29160. case VertexBuffer.ColorKind:
  29161. case VertexBuffer.MatricesIndicesKind:
  29162. case VertexBuffer.MatricesIndicesExtraKind:
  29163. case VertexBuffer.MatricesWeightsKind:
  29164. case VertexBuffer.MatricesWeightsExtraKind:
  29165. case VertexBuffer.TangentKind:
  29166. return 4;
  29167. default:
  29168. throw new Error("Invalid kind '" + kind + "'");
  29169. }
  29170. };
  29171. /**
  29172. * Gets the byte length of the given type.
  29173. * @param type the type
  29174. * @returns the number of bytes
  29175. */
  29176. VertexBuffer.GetTypeByteLength = function (type) {
  29177. switch (type) {
  29178. case VertexBuffer.BYTE:
  29179. case VertexBuffer.UNSIGNED_BYTE:
  29180. return 1;
  29181. case VertexBuffer.SHORT:
  29182. case VertexBuffer.UNSIGNED_SHORT:
  29183. return 2;
  29184. case VertexBuffer.INT:
  29185. case VertexBuffer.FLOAT:
  29186. return 4;
  29187. default:
  29188. throw new Error("Invalid type '" + type + "'");
  29189. }
  29190. };
  29191. /**
  29192. * Enumerates each value of the given parameters as numbers.
  29193. * @param data the data to enumerate
  29194. * @param byteOffset the byte offset of the data
  29195. * @param byteStride the byte stride of the data
  29196. * @param componentCount the number of components per element
  29197. * @param componentType the type of the component
  29198. * @param count the total number of components
  29199. * @param normalized whether the data is normalized
  29200. * @param callback the callback function called for each value
  29201. */
  29202. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29203. if (data instanceof Array) {
  29204. var offset = byteOffset / 4;
  29205. var stride = byteStride / 4;
  29206. for (var index = 0; index < count; index += componentCount) {
  29207. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29208. callback(data[offset + componentIndex], index + componentIndex);
  29209. }
  29210. offset += stride;
  29211. }
  29212. }
  29213. else {
  29214. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29215. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29216. for (var index = 0; index < count; index += componentCount) {
  29217. var componentByteOffset = byteOffset;
  29218. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29219. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29220. callback(value, index + componentIndex);
  29221. componentByteOffset += componentByteLength;
  29222. }
  29223. byteOffset += byteStride;
  29224. }
  29225. }
  29226. };
  29227. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29228. switch (type) {
  29229. case VertexBuffer.BYTE: {
  29230. var value = dataView.getInt8(byteOffset);
  29231. if (normalized) {
  29232. value = (value + 0.5) / 127.5;
  29233. }
  29234. return value;
  29235. }
  29236. case VertexBuffer.UNSIGNED_BYTE: {
  29237. var value = dataView.getUint8(byteOffset);
  29238. if (normalized) {
  29239. value = value / 255;
  29240. }
  29241. return value;
  29242. }
  29243. case VertexBuffer.SHORT: {
  29244. var value = dataView.getInt16(byteOffset, true);
  29245. if (normalized) {
  29246. value = (value + 0.5) / 16383.5;
  29247. }
  29248. return value;
  29249. }
  29250. case VertexBuffer.UNSIGNED_SHORT: {
  29251. var value = dataView.getUint16(byteOffset, true);
  29252. if (normalized) {
  29253. value = value / 65535;
  29254. }
  29255. return value;
  29256. }
  29257. case VertexBuffer.FLOAT: {
  29258. return dataView.getFloat32(byteOffset, true);
  29259. }
  29260. default: {
  29261. throw new Error("Invalid component type " + type);
  29262. }
  29263. }
  29264. };
  29265. /**
  29266. * The byte type.
  29267. */
  29268. VertexBuffer.BYTE = 5120;
  29269. /**
  29270. * The unsigned byte type.
  29271. */
  29272. VertexBuffer.UNSIGNED_BYTE = 5121;
  29273. /**
  29274. * The short type.
  29275. */
  29276. VertexBuffer.SHORT = 5122;
  29277. /**
  29278. * The unsigned short type.
  29279. */
  29280. VertexBuffer.UNSIGNED_SHORT = 5123;
  29281. /**
  29282. * The integer type.
  29283. */
  29284. VertexBuffer.INT = 5124;
  29285. /**
  29286. * The unsigned integer type.
  29287. */
  29288. VertexBuffer.UNSIGNED_INT = 5125;
  29289. /**
  29290. * The float type.
  29291. */
  29292. VertexBuffer.FLOAT = 5126;
  29293. // Enums
  29294. VertexBuffer._PositionKind = "position";
  29295. VertexBuffer._NormalKind = "normal";
  29296. VertexBuffer._TangentKind = "tangent";
  29297. VertexBuffer._UVKind = "uv";
  29298. VertexBuffer._UV2Kind = "uv2";
  29299. VertexBuffer._UV3Kind = "uv3";
  29300. VertexBuffer._UV4Kind = "uv4";
  29301. VertexBuffer._UV5Kind = "uv5";
  29302. VertexBuffer._UV6Kind = "uv6";
  29303. VertexBuffer._ColorKind = "color";
  29304. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29305. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29306. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29307. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29308. return VertexBuffer;
  29309. }());
  29310. BABYLON.VertexBuffer = VertexBuffer;
  29311. })(BABYLON || (BABYLON = {}));
  29312. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29313. var BABYLON;
  29314. (function (BABYLON) {
  29315. /**
  29316. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29317. */
  29318. var DummyInternalTextureTracker = /** @class */ (function () {
  29319. function DummyInternalTextureTracker() {
  29320. /**
  29321. * Gets or set the previous tracker in the list
  29322. */
  29323. this.previous = null;
  29324. /**
  29325. * Gets or set the next tracker in the list
  29326. */
  29327. this.next = null;
  29328. }
  29329. return DummyInternalTextureTracker;
  29330. }());
  29331. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29332. })(BABYLON || (BABYLON = {}));
  29333. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29334. var BABYLON;
  29335. (function (BABYLON) {
  29336. /**
  29337. * Class used to store data associated with WebGL texture data for the engine
  29338. * This class should not be used directly
  29339. */
  29340. var InternalTexture = /** @class */ (function () {
  29341. /**
  29342. * Creates a new InternalTexture
  29343. * @param engine defines the engine to use
  29344. * @param dataSource defines the type of data that will be used
  29345. */
  29346. function InternalTexture(engine, dataSource) {
  29347. /**
  29348. * Observable called when the texture is loaded
  29349. */
  29350. this.onLoadedObservable = new BABYLON.Observable();
  29351. /**
  29352. * Gets or set the previous tracker in the list
  29353. */
  29354. this.previous = null;
  29355. /**
  29356. * Gets or set the next tracker in the list
  29357. */
  29358. this.next = null;
  29359. // Private
  29360. /** @ignore */
  29361. this._initialSlot = -1;
  29362. /** @ignore */
  29363. this._designatedSlot = -1;
  29364. /** @ignore */
  29365. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29366. /** @ignore */
  29367. this._comparisonFunction = 0;
  29368. /** @ignore */
  29369. this._references = 1;
  29370. this._engine = engine;
  29371. this._dataSource = dataSource;
  29372. this._webGLTexture = engine._createTexture();
  29373. }
  29374. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29375. /**
  29376. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29377. */
  29378. get: function () {
  29379. return this._dataSource;
  29380. },
  29381. enumerable: true,
  29382. configurable: true
  29383. });
  29384. /**
  29385. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29386. */
  29387. InternalTexture.prototype.incrementReferences = function () {
  29388. this._references++;
  29389. };
  29390. /**
  29391. * Change the size of the texture (not the size of the content)
  29392. * @param width defines the new width
  29393. * @param height defines the new height
  29394. * @param depth defines the new depth (1 by default)
  29395. */
  29396. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29397. if (depth === void 0) { depth = 1; }
  29398. this.width = width;
  29399. this.height = height;
  29400. this.depth = depth;
  29401. this.baseWidth = width;
  29402. this.baseHeight = height;
  29403. this.baseDepth = depth;
  29404. this._size = width * height * depth;
  29405. };
  29406. /** @ignore */
  29407. InternalTexture.prototype._rebuild = function () {
  29408. var _this = this;
  29409. var proxy;
  29410. this.isReady = false;
  29411. this._cachedCoordinatesMode = null;
  29412. this._cachedWrapU = null;
  29413. this._cachedWrapV = null;
  29414. this._cachedAnisotropicFilteringLevel = null;
  29415. switch (this._dataSource) {
  29416. case InternalTexture.DATASOURCE_TEMP:
  29417. return;
  29418. case InternalTexture.DATASOURCE_URL:
  29419. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29420. _this.isReady = true;
  29421. }, null, this._buffer, undefined, this.format);
  29422. proxy._swapAndDie(this);
  29423. return;
  29424. case InternalTexture.DATASOURCE_RAW:
  29425. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29426. proxy._swapAndDie(this);
  29427. this.isReady = true;
  29428. return;
  29429. case InternalTexture.DATASOURCE_RAW3D:
  29430. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29431. proxy._swapAndDie(this);
  29432. this.isReady = true;
  29433. return;
  29434. case InternalTexture.DATASOURCE_DYNAMIC:
  29435. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29436. proxy._swapAndDie(this);
  29437. // The engine will make sure to update content so no need to flag it as isReady = true
  29438. return;
  29439. case InternalTexture.DATASOURCE_RENDERTARGET:
  29440. var options = new BABYLON.RenderTargetCreationOptions();
  29441. options.generateDepthBuffer = this._generateDepthBuffer;
  29442. options.generateMipMaps = this.generateMipMaps;
  29443. options.generateStencilBuffer = this._generateStencilBuffer;
  29444. options.samplingMode = this.samplingMode;
  29445. options.type = this.type;
  29446. if (this.isCube) {
  29447. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29448. }
  29449. else {
  29450. var size = {
  29451. width: this.width,
  29452. height: this.height
  29453. };
  29454. proxy = this._engine.createRenderTargetTexture(size, options);
  29455. }
  29456. proxy._swapAndDie(this);
  29457. this.isReady = true;
  29458. return;
  29459. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29460. var depthTextureOptions = {
  29461. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29462. comparisonFunction: this._comparisonFunction,
  29463. generateStencil: this._generateStencilBuffer,
  29464. isCube: this.isCube
  29465. };
  29466. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29467. proxy._swapAndDie(this);
  29468. this.isReady = true;
  29469. return;
  29470. case InternalTexture.DATASOURCE_CUBE:
  29471. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29472. _this.isReady = true;
  29473. }, null, this.format, this._extension);
  29474. proxy._swapAndDie(this);
  29475. return;
  29476. case InternalTexture.DATASOURCE_CUBERAW:
  29477. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29478. proxy._swapAndDie(this);
  29479. this.isReady = true;
  29480. return;
  29481. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29482. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29483. if (proxy) {
  29484. proxy._swapAndDie(_this);
  29485. }
  29486. _this.isReady = true;
  29487. }, null, this.format, this._extension);
  29488. return;
  29489. }
  29490. };
  29491. InternalTexture.prototype._swapAndDie = function (target) {
  29492. target._webGLTexture = this._webGLTexture;
  29493. if (this._framebuffer) {
  29494. target._framebuffer = this._framebuffer;
  29495. }
  29496. if (this._depthStencilBuffer) {
  29497. target._depthStencilBuffer = this._depthStencilBuffer;
  29498. }
  29499. if (this._lodTextureHigh) {
  29500. if (target._lodTextureHigh) {
  29501. target._lodTextureHigh.dispose();
  29502. }
  29503. target._lodTextureHigh = this._lodTextureHigh;
  29504. }
  29505. if (this._lodTextureMid) {
  29506. if (target._lodTextureMid) {
  29507. target._lodTextureMid.dispose();
  29508. }
  29509. target._lodTextureMid = this._lodTextureMid;
  29510. }
  29511. if (this._lodTextureLow) {
  29512. if (target._lodTextureLow) {
  29513. target._lodTextureLow.dispose();
  29514. }
  29515. target._lodTextureLow = this._lodTextureLow;
  29516. }
  29517. var cache = this._engine.getLoadedTexturesCache();
  29518. var index = cache.indexOf(this);
  29519. if (index !== -1) {
  29520. cache.splice(index, 1);
  29521. }
  29522. };
  29523. /**
  29524. * Dispose the current allocated resources
  29525. */
  29526. InternalTexture.prototype.dispose = function () {
  29527. if (!this._webGLTexture) {
  29528. return;
  29529. }
  29530. this._references--;
  29531. if (this._references === 0) {
  29532. this._engine._releaseTexture(this);
  29533. this._webGLTexture = null;
  29534. this.previous = null;
  29535. this.next = null;
  29536. }
  29537. };
  29538. /**
  29539. * The source of the texture data is unknown
  29540. */
  29541. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29542. /**
  29543. * Texture data comes from an URL
  29544. */
  29545. InternalTexture.DATASOURCE_URL = 1;
  29546. /**
  29547. * Texture data is only used for temporary storage
  29548. */
  29549. InternalTexture.DATASOURCE_TEMP = 2;
  29550. /**
  29551. * Texture data comes from raw data (ArrayBuffer)
  29552. */
  29553. InternalTexture.DATASOURCE_RAW = 3;
  29554. /**
  29555. * Texture content is dynamic (video or dynamic texture)
  29556. */
  29557. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29558. /**
  29559. * Texture content is generated by rendering to it
  29560. */
  29561. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29562. /**
  29563. * Texture content is part of a multi render target process
  29564. */
  29565. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29566. /**
  29567. * Texture data comes from a cube data file
  29568. */
  29569. InternalTexture.DATASOURCE_CUBE = 7;
  29570. /**
  29571. * Texture data comes from a raw cube data
  29572. */
  29573. InternalTexture.DATASOURCE_CUBERAW = 8;
  29574. /**
  29575. * Texture data come from a prefiltered cube data file
  29576. */
  29577. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29578. /**
  29579. * Texture content is raw 3D data
  29580. */
  29581. InternalTexture.DATASOURCE_RAW3D = 10;
  29582. /**
  29583. * Texture content is a depth texture
  29584. */
  29585. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29586. return InternalTexture;
  29587. }());
  29588. BABYLON.InternalTexture = InternalTexture;
  29589. })(BABYLON || (BABYLON = {}));
  29590. //# sourceMappingURL=babylon.internalTexture.js.map
  29591. var BABYLON;
  29592. (function (BABYLON) {
  29593. var BaseTexture = /** @class */ (function () {
  29594. function BaseTexture(scene) {
  29595. this._hasAlpha = false;
  29596. this.getAlphaFromRGB = false;
  29597. this.level = 1;
  29598. this.coordinatesIndex = 0;
  29599. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29600. /**
  29601. * | Value | Type | Description |
  29602. * | ----- | ------------------ | ----------- |
  29603. * | 0 | CLAMP_ADDRESSMODE | |
  29604. * | 1 | WRAP_ADDRESSMODE | |
  29605. * | 2 | MIRROR_ADDRESSMODE | |
  29606. */
  29607. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29608. /**
  29609. * | Value | Type | Description |
  29610. * | ----- | ------------------ | ----------- |
  29611. * | 0 | CLAMP_ADDRESSMODE | |
  29612. * | 1 | WRAP_ADDRESSMODE | |
  29613. * | 2 | MIRROR_ADDRESSMODE | |
  29614. */
  29615. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29616. /**
  29617. * | Value | Type | Description |
  29618. * | ----- | ------------------ | ----------- |
  29619. * | 0 | CLAMP_ADDRESSMODE | |
  29620. * | 1 | WRAP_ADDRESSMODE | |
  29621. * | 2 | MIRROR_ADDRESSMODE | |
  29622. */
  29623. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29624. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29625. this.isCube = false;
  29626. this.is3D = false;
  29627. this.gammaSpace = true;
  29628. this.invertZ = false;
  29629. this.lodLevelInAlpha = false;
  29630. this.lodGenerationOffset = 0.0;
  29631. this.lodGenerationScale = 0.8;
  29632. this.isRenderTarget = false;
  29633. this.animations = new Array();
  29634. /**
  29635. * An event triggered when the texture is disposed.
  29636. */
  29637. this.onDisposeObservable = new BABYLON.Observable();
  29638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29639. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29640. if (this._scene) {
  29641. this._scene.textures.push(this);
  29642. }
  29643. this._uid = null;
  29644. }
  29645. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29646. get: function () {
  29647. return this._hasAlpha;
  29648. },
  29649. set: function (value) {
  29650. if (this._hasAlpha === value) {
  29651. return;
  29652. }
  29653. this._hasAlpha = value;
  29654. if (this._scene) {
  29655. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29656. }
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29662. get: function () {
  29663. return this._coordinatesMode;
  29664. },
  29665. /**
  29666. * How a texture is mapped.
  29667. *
  29668. * | Value | Type | Description |
  29669. * | ----- | ----------------------------------- | ----------- |
  29670. * | 0 | EXPLICIT_MODE | |
  29671. * | 1 | SPHERICAL_MODE | |
  29672. * | 2 | PLANAR_MODE | |
  29673. * | 3 | CUBIC_MODE | |
  29674. * | 4 | PROJECTION_MODE | |
  29675. * | 5 | SKYBOX_MODE | |
  29676. * | 6 | INVCUBIC_MODE | |
  29677. * | 7 | EQUIRECTANGULAR_MODE | |
  29678. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29679. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29680. */
  29681. set: function (value) {
  29682. if (this._coordinatesMode === value) {
  29683. return;
  29684. }
  29685. this._coordinatesMode = value;
  29686. if (this._scene) {
  29687. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29688. }
  29689. },
  29690. enumerable: true,
  29691. configurable: true
  29692. });
  29693. Object.defineProperty(BaseTexture.prototype, "uid", {
  29694. get: function () {
  29695. if (!this._uid) {
  29696. this._uid = BABYLON.Tools.RandomId();
  29697. }
  29698. return this._uid;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. BaseTexture.prototype.toString = function () {
  29704. return this.name;
  29705. };
  29706. BaseTexture.prototype.getClassName = function () {
  29707. return "BaseTexture";
  29708. };
  29709. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29710. set: function (callback) {
  29711. if (this._onDisposeObserver) {
  29712. this.onDisposeObservable.remove(this._onDisposeObserver);
  29713. }
  29714. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29715. },
  29716. enumerable: true,
  29717. configurable: true
  29718. });
  29719. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29720. get: function () {
  29721. return true;
  29722. },
  29723. enumerable: true,
  29724. configurable: true
  29725. });
  29726. BaseTexture.prototype.getScene = function () {
  29727. return this._scene;
  29728. };
  29729. BaseTexture.prototype.getTextureMatrix = function () {
  29730. return BABYLON.Matrix.IdentityReadOnly;
  29731. };
  29732. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29733. return BABYLON.Matrix.IdentityReadOnly;
  29734. };
  29735. BaseTexture.prototype.getInternalTexture = function () {
  29736. return this._texture;
  29737. };
  29738. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29739. return !this.isBlocking || this.isReady();
  29740. };
  29741. BaseTexture.prototype.isReady = function () {
  29742. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29743. this.delayLoad();
  29744. return false;
  29745. }
  29746. if (this._texture) {
  29747. return this._texture.isReady;
  29748. }
  29749. return false;
  29750. };
  29751. BaseTexture.prototype.getSize = function () {
  29752. if (this._texture && this._texture.width) {
  29753. return new BABYLON.Size(this._texture.width, this._texture.height);
  29754. }
  29755. if (this._texture && this._texture._size) {
  29756. return new BABYLON.Size(this._texture._size, this._texture._size);
  29757. }
  29758. return BABYLON.Size.Zero();
  29759. };
  29760. BaseTexture.prototype.getBaseSize = function () {
  29761. if (!this.isReady() || !this._texture)
  29762. return BABYLON.Size.Zero();
  29763. if (this._texture._size) {
  29764. return new BABYLON.Size(this._texture._size, this._texture._size);
  29765. }
  29766. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29767. };
  29768. BaseTexture.prototype.scale = function (ratio) {
  29769. };
  29770. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29771. get: function () {
  29772. return false;
  29773. },
  29774. enumerable: true,
  29775. configurable: true
  29776. });
  29777. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29778. if (!this._scene) {
  29779. return null;
  29780. }
  29781. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29782. for (var index = 0; index < texturesCache.length; index++) {
  29783. var texturesCacheEntry = texturesCache[index];
  29784. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29785. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29786. texturesCacheEntry.incrementReferences();
  29787. return texturesCacheEntry;
  29788. }
  29789. }
  29790. }
  29791. return null;
  29792. };
  29793. BaseTexture.prototype._rebuild = function () {
  29794. };
  29795. BaseTexture.prototype.delayLoad = function () {
  29796. };
  29797. BaseTexture.prototype.clone = function () {
  29798. return null;
  29799. };
  29800. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29801. get: function () {
  29802. if (!this._texture) {
  29803. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29804. }
  29805. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29806. },
  29807. enumerable: true,
  29808. configurable: true
  29809. });
  29810. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29811. get: function () {
  29812. if (!this._texture) {
  29813. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29814. }
  29815. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29816. },
  29817. enumerable: true,
  29818. configurable: true
  29819. });
  29820. BaseTexture.prototype.readPixels = function (faceIndex) {
  29821. if (faceIndex === void 0) { faceIndex = 0; }
  29822. if (!this._texture) {
  29823. return null;
  29824. }
  29825. var size = this.getSize();
  29826. var scene = this.getScene();
  29827. if (!scene) {
  29828. return null;
  29829. }
  29830. var engine = scene.getEngine();
  29831. if (this._texture.isCube) {
  29832. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29833. }
  29834. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29835. };
  29836. BaseTexture.prototype.releaseInternalTexture = function () {
  29837. if (this._texture) {
  29838. this._texture.dispose();
  29839. this._texture = null;
  29840. }
  29841. };
  29842. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29843. get: function () {
  29844. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29845. return null;
  29846. }
  29847. if (!this._texture._sphericalPolynomial) {
  29848. this._texture._sphericalPolynomial =
  29849. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29850. }
  29851. return this._texture._sphericalPolynomial;
  29852. },
  29853. set: function (value) {
  29854. if (this._texture) {
  29855. this._texture._sphericalPolynomial = value;
  29856. }
  29857. },
  29858. enumerable: true,
  29859. configurable: true
  29860. });
  29861. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29862. get: function () {
  29863. if (this._texture) {
  29864. return this._texture._lodTextureHigh;
  29865. }
  29866. return null;
  29867. },
  29868. enumerable: true,
  29869. configurable: true
  29870. });
  29871. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29872. get: function () {
  29873. if (this._texture) {
  29874. return this._texture._lodTextureMid;
  29875. }
  29876. return null;
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29882. get: function () {
  29883. if (this._texture) {
  29884. return this._texture._lodTextureLow;
  29885. }
  29886. return null;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. BaseTexture.prototype.dispose = function () {
  29892. if (!this._scene) {
  29893. return;
  29894. }
  29895. // Animations
  29896. this._scene.stopAnimation(this);
  29897. // Remove from scene
  29898. this._scene._removePendingData(this);
  29899. var index = this._scene.textures.indexOf(this);
  29900. if (index >= 0) {
  29901. this._scene.textures.splice(index, 1);
  29902. }
  29903. if (this._texture === undefined) {
  29904. return;
  29905. }
  29906. // Release
  29907. this.releaseInternalTexture();
  29908. // Callback
  29909. this.onDisposeObservable.notifyObservers(this);
  29910. this.onDisposeObservable.clear();
  29911. };
  29912. BaseTexture.prototype.serialize = function () {
  29913. if (!this.name) {
  29914. return null;
  29915. }
  29916. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29917. // Animations
  29918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29919. return serializationObject;
  29920. };
  29921. BaseTexture.WhenAllReady = function (textures, callback) {
  29922. var numRemaining = textures.length;
  29923. if (numRemaining === 0) {
  29924. callback();
  29925. return;
  29926. }
  29927. var _loop_1 = function () {
  29928. texture = textures[i];
  29929. if (texture.isReady()) {
  29930. if (--numRemaining === 0) {
  29931. callback();
  29932. }
  29933. }
  29934. else {
  29935. onLoadObservable = texture.onLoadObservable;
  29936. var onLoadCallback_1 = function () {
  29937. onLoadObservable.removeCallback(onLoadCallback_1);
  29938. if (--numRemaining === 0) {
  29939. callback();
  29940. }
  29941. };
  29942. onLoadObservable.add(onLoadCallback_1);
  29943. }
  29944. };
  29945. var texture, onLoadObservable;
  29946. for (var i = 0; i < textures.length; i++) {
  29947. _loop_1();
  29948. }
  29949. };
  29950. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29951. __decorate([
  29952. BABYLON.serialize()
  29953. ], BaseTexture.prototype, "name", void 0);
  29954. __decorate([
  29955. BABYLON.serialize("hasAlpha")
  29956. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29957. __decorate([
  29958. BABYLON.serialize()
  29959. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29960. __decorate([
  29961. BABYLON.serialize()
  29962. ], BaseTexture.prototype, "level", void 0);
  29963. __decorate([
  29964. BABYLON.serialize()
  29965. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29966. __decorate([
  29967. BABYLON.serialize("coordinatesMode")
  29968. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29969. __decorate([
  29970. BABYLON.serialize()
  29971. ], BaseTexture.prototype, "wrapU", void 0);
  29972. __decorate([
  29973. BABYLON.serialize()
  29974. ], BaseTexture.prototype, "wrapV", void 0);
  29975. __decorate([
  29976. BABYLON.serialize()
  29977. ], BaseTexture.prototype, "wrapR", void 0);
  29978. __decorate([
  29979. BABYLON.serialize()
  29980. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29981. __decorate([
  29982. BABYLON.serialize()
  29983. ], BaseTexture.prototype, "isCube", void 0);
  29984. __decorate([
  29985. BABYLON.serialize()
  29986. ], BaseTexture.prototype, "is3D", void 0);
  29987. __decorate([
  29988. BABYLON.serialize()
  29989. ], BaseTexture.prototype, "gammaSpace", void 0);
  29990. __decorate([
  29991. BABYLON.serialize()
  29992. ], BaseTexture.prototype, "invertZ", void 0);
  29993. __decorate([
  29994. BABYLON.serialize()
  29995. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29996. __decorate([
  29997. BABYLON.serialize()
  29998. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29999. __decorate([
  30000. BABYLON.serialize()
  30001. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30002. __decorate([
  30003. BABYLON.serialize()
  30004. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30005. return BaseTexture;
  30006. }());
  30007. BABYLON.BaseTexture = BaseTexture;
  30008. })(BABYLON || (BABYLON = {}));
  30009. //# sourceMappingURL=babylon.baseTexture.js.map
  30010. var BABYLON;
  30011. (function (BABYLON) {
  30012. var Texture = /** @class */ (function (_super) {
  30013. __extends(Texture, _super);
  30014. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30015. if (noMipmap === void 0) { noMipmap = false; }
  30016. if (invertY === void 0) { invertY = true; }
  30017. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30018. if (onLoad === void 0) { onLoad = null; }
  30019. if (onError === void 0) { onError = null; }
  30020. if (buffer === void 0) { buffer = null; }
  30021. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30022. var _this = _super.call(this, scene) || this;
  30023. _this.uOffset = 0;
  30024. _this.vOffset = 0;
  30025. _this.uScale = 1.0;
  30026. _this.vScale = 1.0;
  30027. _this.uAng = 0;
  30028. _this.vAng = 0;
  30029. _this.wAng = 0;
  30030. _this._isBlocking = true;
  30031. _this.name = url || "";
  30032. _this.url = url;
  30033. _this._noMipmap = noMipmap;
  30034. _this._invertY = invertY;
  30035. _this._samplingMode = samplingMode;
  30036. _this._buffer = buffer;
  30037. _this._deleteBuffer = deleteBuffer;
  30038. if (format) {
  30039. _this._format = format;
  30040. }
  30041. scene = _this.getScene();
  30042. if (!scene) {
  30043. return _this;
  30044. }
  30045. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30046. var load = function () {
  30047. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30048. _this.onLoadObservable.notifyObservers(_this);
  30049. }
  30050. if (onLoad) {
  30051. onLoad();
  30052. }
  30053. if (!_this.isBlocking && scene) {
  30054. scene.resetCachedMaterial();
  30055. }
  30056. };
  30057. if (!_this.url) {
  30058. _this._delayedOnLoad = load;
  30059. _this._delayedOnError = onError;
  30060. return _this;
  30061. }
  30062. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30063. if (!_this._texture) {
  30064. if (!scene.useDelayedTextureLoading) {
  30065. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30066. if (deleteBuffer) {
  30067. delete _this._buffer;
  30068. }
  30069. }
  30070. else {
  30071. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30072. _this._delayedOnLoad = load;
  30073. _this._delayedOnError = onError;
  30074. }
  30075. }
  30076. else {
  30077. if (_this._texture.isReady) {
  30078. BABYLON.Tools.SetImmediate(function () { return load(); });
  30079. }
  30080. else {
  30081. _this._texture.onLoadedObservable.add(load);
  30082. }
  30083. }
  30084. return _this;
  30085. }
  30086. Object.defineProperty(Texture.prototype, "noMipmap", {
  30087. get: function () {
  30088. return this._noMipmap;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. Object.defineProperty(Texture.prototype, "isBlocking", {
  30094. get: function () {
  30095. return this._isBlocking;
  30096. },
  30097. set: function (value) {
  30098. this._isBlocking = value;
  30099. },
  30100. enumerable: true,
  30101. configurable: true
  30102. });
  30103. Object.defineProperty(Texture.prototype, "samplingMode", {
  30104. get: function () {
  30105. return this._samplingMode;
  30106. },
  30107. enumerable: true,
  30108. configurable: true
  30109. });
  30110. Texture.prototype.updateURL = function (url) {
  30111. this.url = url;
  30112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30113. this.delayLoad();
  30114. };
  30115. Texture.prototype.delayLoad = function () {
  30116. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30117. return;
  30118. }
  30119. var scene = this.getScene();
  30120. if (!scene) {
  30121. return;
  30122. }
  30123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30124. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30125. if (!this._texture) {
  30126. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30127. if (this._deleteBuffer) {
  30128. delete this._buffer;
  30129. }
  30130. }
  30131. else {
  30132. if (this._delayedOnLoad) {
  30133. if (this._texture.isReady) {
  30134. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30135. }
  30136. else {
  30137. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30138. }
  30139. }
  30140. }
  30141. this._delayedOnLoad = null;
  30142. this._delayedOnError = null;
  30143. };
  30144. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30145. if (!this._texture) {
  30146. return;
  30147. }
  30148. var scene = this.getScene();
  30149. if (!scene) {
  30150. return;
  30151. }
  30152. this._samplingMode = samplingMode;
  30153. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30154. };
  30155. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30156. x *= this.uScale;
  30157. y *= this.vScale;
  30158. x -= 0.5 * this.uScale;
  30159. y -= 0.5 * this.vScale;
  30160. z -= 0.5;
  30161. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30162. t.x += 0.5 * this.uScale + this.uOffset;
  30163. t.y += 0.5 * this.vScale + this.vOffset;
  30164. t.z += 0.5;
  30165. };
  30166. Texture.prototype.getTextureMatrix = function () {
  30167. var _this = this;
  30168. if (this.uOffset === this._cachedUOffset &&
  30169. this.vOffset === this._cachedVOffset &&
  30170. this.uScale === this._cachedUScale &&
  30171. this.vScale === this._cachedVScale &&
  30172. this.uAng === this._cachedUAng &&
  30173. this.vAng === this._cachedVAng &&
  30174. this.wAng === this._cachedWAng) {
  30175. return this._cachedTextureMatrix;
  30176. }
  30177. this._cachedUOffset = this.uOffset;
  30178. this._cachedVOffset = this.vOffset;
  30179. this._cachedUScale = this.uScale;
  30180. this._cachedVScale = this.vScale;
  30181. this._cachedUAng = this.uAng;
  30182. this._cachedVAng = this.vAng;
  30183. this._cachedWAng = this.wAng;
  30184. if (!this._cachedTextureMatrix) {
  30185. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30186. this._rowGenerationMatrix = new BABYLON.Matrix();
  30187. this._t0 = BABYLON.Vector3.Zero();
  30188. this._t1 = BABYLON.Vector3.Zero();
  30189. this._t2 = BABYLON.Vector3.Zero();
  30190. }
  30191. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30192. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30193. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30194. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30195. this._t1.subtractInPlace(this._t0);
  30196. this._t2.subtractInPlace(this._t0);
  30197. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30198. this._cachedTextureMatrix.m[0] = this._t1.x;
  30199. this._cachedTextureMatrix.m[1] = this._t1.y;
  30200. this._cachedTextureMatrix.m[2] = this._t1.z;
  30201. this._cachedTextureMatrix.m[4] = this._t2.x;
  30202. this._cachedTextureMatrix.m[5] = this._t2.y;
  30203. this._cachedTextureMatrix.m[6] = this._t2.z;
  30204. this._cachedTextureMatrix.m[8] = this._t0.x;
  30205. this._cachedTextureMatrix.m[9] = this._t0.y;
  30206. this._cachedTextureMatrix.m[10] = this._t0.z;
  30207. var scene = this.getScene();
  30208. if (!scene) {
  30209. return this._cachedTextureMatrix;
  30210. }
  30211. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30212. return mat.hasTexture(_this);
  30213. });
  30214. return this._cachedTextureMatrix;
  30215. };
  30216. Texture.prototype.getReflectionTextureMatrix = function () {
  30217. var _this = this;
  30218. var scene = this.getScene();
  30219. if (!scene) {
  30220. return this._cachedTextureMatrix;
  30221. }
  30222. if (this.uOffset === this._cachedUOffset &&
  30223. this.vOffset === this._cachedVOffset &&
  30224. this.uScale === this._cachedUScale &&
  30225. this.vScale === this._cachedVScale &&
  30226. this.coordinatesMode === this._cachedCoordinatesMode) {
  30227. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30228. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30229. return this._cachedTextureMatrix;
  30230. }
  30231. }
  30232. else {
  30233. return this._cachedTextureMatrix;
  30234. }
  30235. }
  30236. if (!this._cachedTextureMatrix) {
  30237. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30238. }
  30239. if (!this._projectionModeMatrix) {
  30240. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30241. }
  30242. this._cachedUOffset = this.uOffset;
  30243. this._cachedVOffset = this.vOffset;
  30244. this._cachedUScale = this.uScale;
  30245. this._cachedVScale = this.vScale;
  30246. this._cachedCoordinatesMode = this.coordinatesMode;
  30247. switch (this.coordinatesMode) {
  30248. case Texture.PLANAR_MODE:
  30249. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30250. this._cachedTextureMatrix[0] = this.uScale;
  30251. this._cachedTextureMatrix[5] = this.vScale;
  30252. this._cachedTextureMatrix[12] = this.uOffset;
  30253. this._cachedTextureMatrix[13] = this.vOffset;
  30254. break;
  30255. case Texture.PROJECTION_MODE:
  30256. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30257. this._projectionModeMatrix.m[0] = 0.5;
  30258. this._projectionModeMatrix.m[5] = -0.5;
  30259. this._projectionModeMatrix.m[10] = 0.0;
  30260. this._projectionModeMatrix.m[12] = 0.5;
  30261. this._projectionModeMatrix.m[13] = 0.5;
  30262. this._projectionModeMatrix.m[14] = 1.0;
  30263. this._projectionModeMatrix.m[15] = 1.0;
  30264. var projectionMatrix = scene.getProjectionMatrix();
  30265. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30266. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30267. break;
  30268. default:
  30269. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30270. break;
  30271. }
  30272. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30273. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30274. });
  30275. return this._cachedTextureMatrix;
  30276. };
  30277. Texture.prototype.clone = function () {
  30278. var _this = this;
  30279. return BABYLON.SerializationHelper.Clone(function () {
  30280. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30281. }, this);
  30282. };
  30283. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30284. get: function () {
  30285. if (!this._onLoadObservable) {
  30286. this._onLoadObservable = new BABYLON.Observable();
  30287. }
  30288. return this._onLoadObservable;
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. Texture.prototype.serialize = function () {
  30294. var serializationObject = _super.prototype.serialize.call(this);
  30295. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30296. serializationObject.base64String = this._buffer;
  30297. serializationObject.name = serializationObject.name.replace("data:", "");
  30298. }
  30299. serializationObject.invertY = this._invertY;
  30300. serializationObject.samplingMode = this.samplingMode;
  30301. return serializationObject;
  30302. };
  30303. Texture.prototype.getClassName = function () {
  30304. return "Texture";
  30305. };
  30306. Texture.prototype.dispose = function () {
  30307. _super.prototype.dispose.call(this);
  30308. if (this.onLoadObservable) {
  30309. this.onLoadObservable.clear();
  30310. this._onLoadObservable = null;
  30311. }
  30312. this._delayedOnLoad = null;
  30313. this._delayedOnError = null;
  30314. };
  30315. // Statics
  30316. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30317. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30318. if (onLoad === void 0) { onLoad = null; }
  30319. if (onError === void 0) { onError = null; }
  30320. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30321. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30322. };
  30323. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30324. if (parsedTexture.customType) {
  30325. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30326. // Update Sampling Mode
  30327. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30328. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30329. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30330. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30331. }
  30332. }
  30333. return parsedCustomTexture;
  30334. }
  30335. if (parsedTexture.isCube) {
  30336. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30337. }
  30338. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30339. return null;
  30340. }
  30341. var texture = BABYLON.SerializationHelper.Parse(function () {
  30342. var generateMipMaps = true;
  30343. if (parsedTexture.noMipmap) {
  30344. generateMipMaps = false;
  30345. }
  30346. if (parsedTexture.mirrorPlane) {
  30347. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30348. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30349. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30350. return mirrorTexture;
  30351. }
  30352. else if (parsedTexture.isRenderTarget) {
  30353. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30354. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30355. return renderTargetTexture;
  30356. }
  30357. else {
  30358. var texture;
  30359. if (parsedTexture.base64String) {
  30360. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30361. }
  30362. else {
  30363. var url = rootUrl + parsedTexture.name;
  30364. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30365. url = parsedTexture.url;
  30366. }
  30367. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30368. }
  30369. return texture;
  30370. }
  30371. }, parsedTexture, scene);
  30372. // Update Sampling Mode
  30373. if (parsedTexture.samplingMode) {
  30374. var sampling = parsedTexture.samplingMode;
  30375. if (texture._samplingMode !== sampling) {
  30376. texture.updateSamplingMode(sampling);
  30377. }
  30378. }
  30379. // Animations
  30380. if (parsedTexture.animations) {
  30381. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30382. var parsedAnimation = parsedTexture.animations[animationIndex];
  30383. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30384. }
  30385. }
  30386. return texture;
  30387. };
  30388. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30389. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30390. if (noMipmap === void 0) { noMipmap = false; }
  30391. if (invertY === void 0) { invertY = true; }
  30392. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30393. if (onLoad === void 0) { onLoad = null; }
  30394. if (onError === void 0) { onError = null; }
  30395. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30396. if (name.substr(0, 5) !== "data:") {
  30397. name = "data:" + name;
  30398. }
  30399. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30400. };
  30401. // Constants
  30402. Texture.NEAREST_SAMPLINGMODE = 1;
  30403. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30404. Texture.BILINEAR_SAMPLINGMODE = 2;
  30405. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30406. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30407. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30408. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30409. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30410. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30411. Texture.NEAREST_LINEAR = 7;
  30412. Texture.NEAREST_NEAREST = 8;
  30413. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30414. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30415. Texture.LINEAR_LINEAR = 11;
  30416. Texture.LINEAR_NEAREST = 12;
  30417. Texture.EXPLICIT_MODE = 0;
  30418. Texture.SPHERICAL_MODE = 1;
  30419. Texture.PLANAR_MODE = 2;
  30420. Texture.CUBIC_MODE = 3;
  30421. Texture.PROJECTION_MODE = 4;
  30422. Texture.SKYBOX_MODE = 5;
  30423. Texture.INVCUBIC_MODE = 6;
  30424. Texture.EQUIRECTANGULAR_MODE = 7;
  30425. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30426. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30427. Texture.CLAMP_ADDRESSMODE = 0;
  30428. Texture.WRAP_ADDRESSMODE = 1;
  30429. Texture.MIRROR_ADDRESSMODE = 2;
  30430. /**
  30431. * 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
  30432. */
  30433. Texture.UseSerializedUrlIfAny = false;
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], Texture.prototype, "url", void 0);
  30437. __decorate([
  30438. BABYLON.serialize()
  30439. ], Texture.prototype, "uOffset", void 0);
  30440. __decorate([
  30441. BABYLON.serialize()
  30442. ], Texture.prototype, "vOffset", void 0);
  30443. __decorate([
  30444. BABYLON.serialize()
  30445. ], Texture.prototype, "uScale", void 0);
  30446. __decorate([
  30447. BABYLON.serialize()
  30448. ], Texture.prototype, "vScale", void 0);
  30449. __decorate([
  30450. BABYLON.serialize()
  30451. ], Texture.prototype, "uAng", void 0);
  30452. __decorate([
  30453. BABYLON.serialize()
  30454. ], Texture.prototype, "vAng", void 0);
  30455. __decorate([
  30456. BABYLON.serialize()
  30457. ], Texture.prototype, "wAng", void 0);
  30458. __decorate([
  30459. BABYLON.serialize()
  30460. ], Texture.prototype, "isBlocking", null);
  30461. return Texture;
  30462. }(BABYLON.BaseTexture));
  30463. BABYLON.Texture = Texture;
  30464. })(BABYLON || (BABYLON = {}));
  30465. //# sourceMappingURL=babylon.texture.js.map
  30466. var BABYLON;
  30467. (function (BABYLON) {
  30468. var _InstancesBatch = /** @class */ (function () {
  30469. function _InstancesBatch() {
  30470. this.mustReturn = false;
  30471. this.visibleInstances = new Array();
  30472. this.renderSelf = new Array();
  30473. }
  30474. return _InstancesBatch;
  30475. }());
  30476. BABYLON._InstancesBatch = _InstancesBatch;
  30477. var Mesh = /** @class */ (function (_super) {
  30478. __extends(Mesh, _super);
  30479. /**
  30480. * @constructor
  30481. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30482. * @param {Scene} scene The scene to add this mesh to.
  30483. * @param {Node} parent The parent of this mesh, if it has one
  30484. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30485. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30486. * When false, achieved by calling a clone(), also passing False.
  30487. * This will make creation of children, recursive.
  30488. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30489. */
  30490. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30491. if (scene === void 0) { scene = null; }
  30492. if (parent === void 0) { parent = null; }
  30493. if (source === void 0) { source = null; }
  30494. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30495. var _this = _super.call(this, name, scene) || this;
  30496. // Events
  30497. /**
  30498. * An event triggered before rendering the mesh
  30499. */
  30500. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30501. /**
  30502. * An event triggered after rendering the mesh
  30503. */
  30504. _this.onAfterRenderObservable = new BABYLON.Observable();
  30505. /**
  30506. * An event triggered before drawing the mesh
  30507. */
  30508. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30509. // Members
  30510. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30511. _this.instances = new Array();
  30512. _this._LODLevels = new Array();
  30513. _this._visibleInstances = {};
  30514. _this._renderIdForInstances = new Array();
  30515. _this._batchCache = new _InstancesBatch();
  30516. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30517. // Use by builder only to know what orientation were the mesh build in.
  30518. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30519. _this.overrideMaterialSideOrientation = null;
  30520. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30521. // Will be used to save a source mesh reference, If any
  30522. _this._source = null;
  30523. scene = _this.getScene();
  30524. if (source) {
  30525. // Source mesh
  30526. _this._source = source;
  30527. // Geometry
  30528. if (source._geometry) {
  30529. source._geometry.applyToMesh(_this);
  30530. }
  30531. // Deep copy
  30532. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30533. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30534. // Metadata
  30535. if (source.metadata && source.metadata.clone) {
  30536. _this.metadata = source.metadata.clone();
  30537. }
  30538. else {
  30539. _this.metadata = source.metadata;
  30540. }
  30541. // Tags
  30542. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30543. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30544. }
  30545. // Parent
  30546. _this.parent = source.parent;
  30547. // Pivot
  30548. _this.setPivotMatrix(source.getPivotMatrix());
  30549. _this.id = name + "." + source.id;
  30550. // Material
  30551. _this.material = source.material;
  30552. var index;
  30553. if (!doNotCloneChildren) {
  30554. // Children
  30555. var directDescendants = source.getDescendants(true);
  30556. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30557. var child = directDescendants[index_1];
  30558. if (child.clone) {
  30559. child.clone(name + "." + child.name, _this);
  30560. }
  30561. }
  30562. }
  30563. // Physics clone
  30564. var physicsEngine = _this.getScene().getPhysicsEngine();
  30565. if (clonePhysicsImpostor && physicsEngine) {
  30566. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30567. if (impostor) {
  30568. _this.physicsImpostor = impostor.clone(_this);
  30569. }
  30570. }
  30571. // Particles
  30572. for (index = 0; index < scene.particleSystems.length; index++) {
  30573. var system = scene.particleSystems[index];
  30574. if (system.emitter === source) {
  30575. system.clone(system.name, _this);
  30576. }
  30577. }
  30578. _this.computeWorldMatrix(true);
  30579. }
  30580. // Parent
  30581. if (parent !== null) {
  30582. _this.parent = parent;
  30583. }
  30584. return _this;
  30585. }
  30586. Object.defineProperty(Mesh, "FRONTSIDE", {
  30587. /**
  30588. * Mesh side orientation : usually the external or front surface
  30589. */
  30590. get: function () {
  30591. return Mesh._FRONTSIDE;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(Mesh, "BACKSIDE", {
  30597. /**
  30598. * Mesh side orientation : usually the internal or back surface
  30599. */
  30600. get: function () {
  30601. return Mesh._BACKSIDE;
  30602. },
  30603. enumerable: true,
  30604. configurable: true
  30605. });
  30606. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30607. /**
  30608. * Mesh side orientation : both internal and external or front and back surfaces
  30609. */
  30610. get: function () {
  30611. return Mesh._DOUBLESIDE;
  30612. },
  30613. enumerable: true,
  30614. configurable: true
  30615. });
  30616. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30617. /**
  30618. * Mesh side orientation : by default, `FRONTSIDE`
  30619. */
  30620. get: function () {
  30621. return Mesh._DEFAULTSIDE;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(Mesh, "NO_CAP", {
  30627. /**
  30628. * Mesh cap setting : no cap
  30629. */
  30630. get: function () {
  30631. return Mesh._NO_CAP;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(Mesh, "CAP_START", {
  30637. /**
  30638. * Mesh cap setting : one cap at the beginning of the mesh
  30639. */
  30640. get: function () {
  30641. return Mesh._CAP_START;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(Mesh, "CAP_END", {
  30647. /**
  30648. * Mesh cap setting : one cap at the end of the mesh
  30649. */
  30650. get: function () {
  30651. return Mesh._CAP_END;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(Mesh, "CAP_ALL", {
  30657. /**
  30658. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30659. */
  30660. get: function () {
  30661. return Mesh._CAP_ALL;
  30662. },
  30663. enumerable: true,
  30664. configurable: true
  30665. });
  30666. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30667. set: function (callback) {
  30668. if (this._onBeforeDrawObserver) {
  30669. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30670. }
  30671. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30677. get: function () {
  30678. return this._morphTargetManager;
  30679. },
  30680. set: function (value) {
  30681. if (this._morphTargetManager === value) {
  30682. return;
  30683. }
  30684. this._morphTargetManager = value;
  30685. this._syncGeometryWithMorphTargetManager();
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Object.defineProperty(Mesh.prototype, "source", {
  30691. get: function () {
  30692. return this._source;
  30693. },
  30694. enumerable: true,
  30695. configurable: true
  30696. });
  30697. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30698. get: function () {
  30699. return this._unIndexed;
  30700. },
  30701. set: function (value) {
  30702. if (this._unIndexed !== value) {
  30703. this._unIndexed = value;
  30704. this._markSubMeshesAsAttributesDirty();
  30705. }
  30706. },
  30707. enumerable: true,
  30708. configurable: true
  30709. });
  30710. // Methods
  30711. /**
  30712. * Returns the string "Mesh".
  30713. */
  30714. Mesh.prototype.getClassName = function () {
  30715. return "Mesh";
  30716. };
  30717. /**
  30718. * Returns a string.
  30719. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30720. */
  30721. Mesh.prototype.toString = function (fullDetails) {
  30722. var ret = _super.prototype.toString.call(this, fullDetails);
  30723. ret += ", n vertices: " + this.getTotalVertices();
  30724. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30725. if (this.animations) {
  30726. for (var i = 0; i < this.animations.length; i++) {
  30727. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30728. }
  30729. }
  30730. if (fullDetails) {
  30731. if (this._geometry) {
  30732. var ib = this.getIndices();
  30733. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30734. if (vb && ib) {
  30735. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30736. }
  30737. }
  30738. else {
  30739. ret += ", flat shading: UNKNOWN";
  30740. }
  30741. }
  30742. return ret;
  30743. };
  30744. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30745. /**
  30746. * True if the mesh has some Levels Of Details (LOD).
  30747. * Returns a boolean.
  30748. */
  30749. get: function () {
  30750. return this._LODLevels.length > 0;
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. /**
  30756. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30757. * @returns an array of {BABYLON.MeshLODLevel}
  30758. */
  30759. Mesh.prototype.getLODLevels = function () {
  30760. return this._LODLevels;
  30761. };
  30762. Mesh.prototype._sortLODLevels = function () {
  30763. this._LODLevels.sort(function (a, b) {
  30764. if (a.distance < b.distance) {
  30765. return 1;
  30766. }
  30767. if (a.distance > b.distance) {
  30768. return -1;
  30769. }
  30770. return 0;
  30771. });
  30772. };
  30773. /**
  30774. * Add a mesh as LOD level triggered at the given distance.
  30775. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30776. * @param {number} distance The distance from the center of the object to show this level
  30777. * @param {Mesh} mesh The mesh to be added as LOD level
  30778. * @return {Mesh} This mesh (for chaining)
  30779. */
  30780. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30781. if (mesh && mesh._masterMesh) {
  30782. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30783. return this;
  30784. }
  30785. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30786. this._LODLevels.push(level);
  30787. if (mesh) {
  30788. mesh._masterMesh = this;
  30789. }
  30790. this._sortLODLevels();
  30791. return this;
  30792. };
  30793. /**
  30794. * Returns the LOD level mesh at the passed distance or null if not found.
  30795. * It is related to the method `addLODLevel(distance, mesh)`.
  30796. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30797. * Returns an object Mesh or `null`.
  30798. */
  30799. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30800. for (var index = 0; index < this._LODLevels.length; index++) {
  30801. var level = this._LODLevels[index];
  30802. if (level.distance === distance) {
  30803. return level.mesh;
  30804. }
  30805. }
  30806. return null;
  30807. };
  30808. /**
  30809. * Remove a mesh from the LOD array
  30810. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30811. * @param {Mesh} mesh The mesh to be removed.
  30812. * @return {Mesh} This mesh (for chaining)
  30813. */
  30814. Mesh.prototype.removeLODLevel = function (mesh) {
  30815. for (var index = 0; index < this._LODLevels.length; index++) {
  30816. if (this._LODLevels[index].mesh === mesh) {
  30817. this._LODLevels.splice(index, 1);
  30818. if (mesh) {
  30819. mesh._masterMesh = null;
  30820. }
  30821. }
  30822. }
  30823. this._sortLODLevels();
  30824. return this;
  30825. };
  30826. /**
  30827. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30828. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30829. */
  30830. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30831. if (!this._LODLevels || this._LODLevels.length === 0) {
  30832. return this;
  30833. }
  30834. var bSphere;
  30835. if (boundingSphere) {
  30836. bSphere = boundingSphere;
  30837. }
  30838. else {
  30839. var boundingInfo = this.getBoundingInfo();
  30840. bSphere = boundingInfo.boundingSphere;
  30841. }
  30842. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30843. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30844. if (this.onLODLevelSelection) {
  30845. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30846. }
  30847. return this;
  30848. }
  30849. for (var index = 0; index < this._LODLevels.length; index++) {
  30850. var level = this._LODLevels[index];
  30851. if (level.distance < distanceToCamera) {
  30852. if (level.mesh) {
  30853. level.mesh._preActivate();
  30854. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30855. }
  30856. if (this.onLODLevelSelection) {
  30857. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30858. }
  30859. return level.mesh;
  30860. }
  30861. }
  30862. if (this.onLODLevelSelection) {
  30863. this.onLODLevelSelection(distanceToCamera, this, this);
  30864. }
  30865. return this;
  30866. };
  30867. Object.defineProperty(Mesh.prototype, "geometry", {
  30868. /**
  30869. * Returns the mesh internal Geometry object.
  30870. */
  30871. get: function () {
  30872. return this._geometry;
  30873. },
  30874. enumerable: true,
  30875. configurable: true
  30876. });
  30877. /**
  30878. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30879. */
  30880. Mesh.prototype.getTotalVertices = function () {
  30881. if (this._geometry === null || this._geometry === undefined) {
  30882. return 0;
  30883. }
  30884. return this._geometry.getTotalVertices();
  30885. };
  30886. /**
  30887. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30888. * 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.
  30889. * You can force the copy with forceCopy === true
  30890. * Returns null if the mesh has no geometry or no vertex buffer.
  30891. * Possible `kind` values :
  30892. * - BABYLON.VertexBuffer.PositionKind
  30893. * - BABYLON.VertexBuffer.UVKind
  30894. * - BABYLON.VertexBuffer.UV2Kind
  30895. * - BABYLON.VertexBuffer.UV3Kind
  30896. * - BABYLON.VertexBuffer.UV4Kind
  30897. * - BABYLON.VertexBuffer.UV5Kind
  30898. * - BABYLON.VertexBuffer.UV6Kind
  30899. * - BABYLON.VertexBuffer.ColorKind
  30900. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30901. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30902. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30903. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30904. */
  30905. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30906. if (!this._geometry) {
  30907. return null;
  30908. }
  30909. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30910. };
  30911. /**
  30912. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30913. * Returns `null` if the mesh has no geometry.
  30914. * Possible `kind` values :
  30915. * - BABYLON.VertexBuffer.PositionKind
  30916. * - BABYLON.VertexBuffer.UVKind
  30917. * - BABYLON.VertexBuffer.UV2Kind
  30918. * - BABYLON.VertexBuffer.UV3Kind
  30919. * - BABYLON.VertexBuffer.UV4Kind
  30920. * - BABYLON.VertexBuffer.UV5Kind
  30921. * - BABYLON.VertexBuffer.UV6Kind
  30922. * - BABYLON.VertexBuffer.ColorKind
  30923. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30924. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30925. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30926. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30927. */
  30928. Mesh.prototype.getVertexBuffer = function (kind) {
  30929. if (!this._geometry) {
  30930. return null;
  30931. }
  30932. return this._geometry.getVertexBuffer(kind);
  30933. };
  30934. /**
  30935. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30936. * Possible `kind` values :
  30937. * - BABYLON.VertexBuffer.PositionKind
  30938. * - BABYLON.VertexBuffer.UVKind
  30939. * - BABYLON.VertexBuffer.UV2Kind
  30940. * - BABYLON.VertexBuffer.UV3Kind
  30941. * - BABYLON.VertexBuffer.UV4Kind
  30942. * - BABYLON.VertexBuffer.UV5Kind
  30943. * - BABYLON.VertexBuffer.UV6Kind
  30944. * - BABYLON.VertexBuffer.ColorKind
  30945. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30946. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30947. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30948. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30949. */
  30950. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30951. if (!this._geometry) {
  30952. if (this._delayInfo) {
  30953. return this._delayInfo.indexOf(kind) !== -1;
  30954. }
  30955. return false;
  30956. }
  30957. return this._geometry.isVerticesDataPresent(kind);
  30958. };
  30959. /**
  30960. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30961. * Possible `kind` values :
  30962. * - BABYLON.VertexBuffer.PositionKind
  30963. * - BABYLON.VertexBuffer.UVKind
  30964. * - BABYLON.VertexBuffer.UV2Kind
  30965. * - BABYLON.VertexBuffer.UV3Kind
  30966. * - BABYLON.VertexBuffer.UV4Kind
  30967. * - BABYLON.VertexBuffer.UV5Kind
  30968. * - BABYLON.VertexBuffer.UV6Kind
  30969. * - BABYLON.VertexBuffer.ColorKind
  30970. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30971. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30972. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30973. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30974. */
  30975. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30976. if (!this._geometry) {
  30977. if (this._delayInfo) {
  30978. return this._delayInfo.indexOf(kind) !== -1;
  30979. }
  30980. return false;
  30981. }
  30982. return this._geometry.isVertexBufferUpdatable(kind);
  30983. };
  30984. /**
  30985. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30986. * Possible `kind` values :
  30987. * - BABYLON.VertexBuffer.PositionKind
  30988. * - BABYLON.VertexBuffer.UVKind
  30989. * - BABYLON.VertexBuffer.UV2Kind
  30990. * - BABYLON.VertexBuffer.UV3Kind
  30991. * - BABYLON.VertexBuffer.UV4Kind
  30992. * - BABYLON.VertexBuffer.UV5Kind
  30993. * - BABYLON.VertexBuffer.UV6Kind
  30994. * - BABYLON.VertexBuffer.ColorKind
  30995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30999. */
  31000. Mesh.prototype.getVerticesDataKinds = function () {
  31001. if (!this._geometry) {
  31002. var result = new Array();
  31003. if (this._delayInfo) {
  31004. this._delayInfo.forEach(function (kind, index, array) {
  31005. result.push(kind);
  31006. });
  31007. }
  31008. return result;
  31009. }
  31010. return this._geometry.getVerticesDataKinds();
  31011. };
  31012. /**
  31013. * Returns a positive integer : the total number of indices in this mesh geometry.
  31014. * Returns zero if the mesh has no geometry.
  31015. */
  31016. Mesh.prototype.getTotalIndices = function () {
  31017. if (!this._geometry) {
  31018. return 0;
  31019. }
  31020. return this._geometry.getTotalIndices();
  31021. };
  31022. /**
  31023. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31024. * 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.
  31025. * Returns an empty array if the mesh has no geometry.
  31026. */
  31027. Mesh.prototype.getIndices = function (copyWhenShared) {
  31028. if (!this._geometry) {
  31029. return [];
  31030. }
  31031. return this._geometry.getIndices(copyWhenShared);
  31032. };
  31033. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31034. get: function () {
  31035. return this._masterMesh !== null && this._masterMesh !== undefined;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. /**
  31041. * Determine if the current mesh is ready to be rendered
  31042. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31043. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31044. * @returns true if all associated assets are ready (material, textures, shaders)
  31045. */
  31046. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31047. if (completeCheck === void 0) { completeCheck = false; }
  31048. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31049. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31050. return false;
  31051. }
  31052. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31053. return false;
  31054. }
  31055. if (!this.subMeshes || this.subMeshes.length === 0) {
  31056. return true;
  31057. }
  31058. if (!completeCheck) {
  31059. return true;
  31060. }
  31061. var engine = this.getEngine();
  31062. var scene = this.getScene();
  31063. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31064. this.computeWorldMatrix();
  31065. var mat = this.material || scene.defaultMaterial;
  31066. if (mat) {
  31067. if (mat.storeEffectOnSubMeshes) {
  31068. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31069. var subMesh = _a[_i];
  31070. var effectiveMaterial = subMesh.getMaterial();
  31071. if (effectiveMaterial) {
  31072. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31073. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31074. return false;
  31075. }
  31076. }
  31077. else {
  31078. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31079. return false;
  31080. }
  31081. }
  31082. }
  31083. }
  31084. }
  31085. else {
  31086. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31087. return false;
  31088. }
  31089. }
  31090. }
  31091. // Shadows
  31092. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31093. var light = _c[_b];
  31094. var generator = light.getShadowGenerator();
  31095. if (generator) {
  31096. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31097. var subMesh = _e[_d];
  31098. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31099. return false;
  31100. }
  31101. }
  31102. }
  31103. }
  31104. // LOD
  31105. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31106. var lod = _g[_f];
  31107. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31108. return false;
  31109. }
  31110. }
  31111. return true;
  31112. };
  31113. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31114. /**
  31115. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31116. * This property is pertinent only for updatable parametric shapes.
  31117. */
  31118. get: function () {
  31119. return this._areNormalsFrozen;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. /**
  31125. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31126. * It has no effect at all on other shapes.
  31127. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31128. * Returns the Mesh.
  31129. */
  31130. Mesh.prototype.freezeNormals = function () {
  31131. this._areNormalsFrozen = true;
  31132. return this;
  31133. };
  31134. /**
  31135. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31136. * It has no effect at all on other shapes.
  31137. * It reactivates the mesh normals computation if it was previously frozen.
  31138. * Returns the Mesh.
  31139. */
  31140. Mesh.prototype.unfreezeNormals = function () {
  31141. this._areNormalsFrozen = false;
  31142. return this;
  31143. };
  31144. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31145. /**
  31146. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31147. */
  31148. set: function (count) {
  31149. this._overridenInstanceCount = count;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. // Methods
  31155. Mesh.prototype._preActivate = function () {
  31156. var sceneRenderId = this.getScene().getRenderId();
  31157. if (this._preActivateId === sceneRenderId) {
  31158. return this;
  31159. }
  31160. this._preActivateId = sceneRenderId;
  31161. this._visibleInstances = null;
  31162. return this;
  31163. };
  31164. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31165. if (this._visibleInstances) {
  31166. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31167. }
  31168. return this;
  31169. };
  31170. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31171. if (!this._visibleInstances) {
  31172. this._visibleInstances = {};
  31173. this._visibleInstances.defaultRenderId = renderId;
  31174. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31175. }
  31176. if (!this._visibleInstances[renderId]) {
  31177. this._visibleInstances[renderId] = new Array();
  31178. }
  31179. this._visibleInstances[renderId].push(instance);
  31180. return this;
  31181. };
  31182. /**
  31183. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31184. * This means the mesh underlying bounding box and sphere are recomputed.
  31185. * Returns the Mesh.
  31186. */
  31187. Mesh.prototype.refreshBoundingInfo = function () {
  31188. return this._refreshBoundingInfo(false);
  31189. };
  31190. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31191. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31192. return this;
  31193. }
  31194. var data = this._getPositionData(applySkeleton);
  31195. if (data) {
  31196. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31197. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31198. }
  31199. if (this.subMeshes) {
  31200. for (var index = 0; index < this.subMeshes.length; index++) {
  31201. this.subMeshes[index].refreshBoundingInfo();
  31202. }
  31203. }
  31204. this._updateBoundingInfo();
  31205. return this;
  31206. };
  31207. Mesh.prototype._getPositionData = function (applySkeleton) {
  31208. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31209. if (data && applySkeleton && this.skeleton) {
  31210. data = BABYLON.Tools.Slice(data);
  31211. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31212. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31213. if (matricesWeightsData && matricesIndicesData) {
  31214. var needExtras = this.numBoneInfluencers > 4;
  31215. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31216. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31217. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31218. var tempVector = BABYLON.Tmp.Vector3[0];
  31219. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31220. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31221. var matWeightIdx = 0;
  31222. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31223. finalMatrix.reset();
  31224. var inf;
  31225. var weight;
  31226. for (inf = 0; inf < 4; inf++) {
  31227. weight = matricesWeightsData[matWeightIdx + inf];
  31228. if (weight <= 0)
  31229. break;
  31230. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31231. finalMatrix.addToSelf(tempMatrix);
  31232. }
  31233. if (needExtras) {
  31234. for (inf = 0; inf < 4; inf++) {
  31235. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31236. if (weight <= 0)
  31237. break;
  31238. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31239. finalMatrix.addToSelf(tempMatrix);
  31240. }
  31241. }
  31242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31243. tempVector.toArray(data, index);
  31244. }
  31245. }
  31246. }
  31247. return data;
  31248. };
  31249. Mesh.prototype._createGlobalSubMesh = function (force) {
  31250. var totalVertices = this.getTotalVertices();
  31251. if (!totalVertices || !this.getIndices()) {
  31252. return null;
  31253. }
  31254. // Check if we need to recreate the submeshes
  31255. if (this.subMeshes && this.subMeshes.length > 0) {
  31256. var ib = this.getIndices();
  31257. if (!ib) {
  31258. return null;
  31259. }
  31260. var totalIndices = ib.length;
  31261. var needToRecreate = false;
  31262. if (force) {
  31263. needToRecreate = true;
  31264. }
  31265. else {
  31266. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31267. var submesh = _a[_i];
  31268. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31269. needToRecreate = true;
  31270. break;
  31271. }
  31272. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31273. needToRecreate = true;
  31274. break;
  31275. }
  31276. }
  31277. }
  31278. if (!needToRecreate) {
  31279. return this.subMeshes[0];
  31280. }
  31281. }
  31282. this.releaseSubMeshes();
  31283. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31284. };
  31285. Mesh.prototype.subdivide = function (count) {
  31286. if (count < 1) {
  31287. return;
  31288. }
  31289. var totalIndices = this.getTotalIndices();
  31290. var subdivisionSize = (totalIndices / count) | 0;
  31291. var offset = 0;
  31292. // Ensure that subdivisionSize is a multiple of 3
  31293. while (subdivisionSize % 3 !== 0) {
  31294. subdivisionSize++;
  31295. }
  31296. this.releaseSubMeshes();
  31297. for (var index = 0; index < count; index++) {
  31298. if (offset >= totalIndices) {
  31299. break;
  31300. }
  31301. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31302. offset += subdivisionSize;
  31303. }
  31304. this.synchronizeInstances();
  31305. };
  31306. /**
  31307. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31308. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31309. * The `data` are either a numeric array either a Float32Array.
  31310. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31311. * 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).
  31312. * Note that a new underlying VertexBuffer object is created each call.
  31313. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31314. *
  31315. * Possible `kind` values :
  31316. * - BABYLON.VertexBuffer.PositionKind
  31317. * - BABYLON.VertexBuffer.UVKind
  31318. * - BABYLON.VertexBuffer.UV2Kind
  31319. * - BABYLON.VertexBuffer.UV3Kind
  31320. * - BABYLON.VertexBuffer.UV4Kind
  31321. * - BABYLON.VertexBuffer.UV5Kind
  31322. * - BABYLON.VertexBuffer.UV6Kind
  31323. * - BABYLON.VertexBuffer.ColorKind
  31324. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31325. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31326. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31327. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31328. *
  31329. * Returns the Mesh.
  31330. */
  31331. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31332. if (updatable === void 0) { updatable = false; }
  31333. if (!this._geometry) {
  31334. var vertexData = new BABYLON.VertexData();
  31335. vertexData.set(data, kind);
  31336. var scene = this.getScene();
  31337. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31338. }
  31339. else {
  31340. this._geometry.setVerticesData(kind, data, updatable, stride);
  31341. }
  31342. return this;
  31343. };
  31344. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31345. if (updatable === void 0) { updatable = true; }
  31346. var vb = this.getVertexBuffer(kind);
  31347. if (!vb || vb.isUpdatable() === updatable) {
  31348. return;
  31349. }
  31350. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31351. };
  31352. /**
  31353. * Sets the mesh VertexBuffer.
  31354. * Returns the Mesh.
  31355. */
  31356. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31357. if (!this._geometry) {
  31358. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31359. }
  31360. this._geometry.setVerticesBuffer(buffer);
  31361. return this;
  31362. };
  31363. /**
  31364. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31365. * If the mesh has no geometry, it is simply returned as it is.
  31366. * The `data` are either a numeric array either a Float32Array.
  31367. * No new underlying VertexBuffer object is created.
  31368. * 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.
  31369. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31370. *
  31371. * Possible `kind` values :
  31372. * - BABYLON.VertexBuffer.PositionKind
  31373. * - BABYLON.VertexBuffer.UVKind
  31374. * - BABYLON.VertexBuffer.UV2Kind
  31375. * - BABYLON.VertexBuffer.UV3Kind
  31376. * - BABYLON.VertexBuffer.UV4Kind
  31377. * - BABYLON.VertexBuffer.UV5Kind
  31378. * - BABYLON.VertexBuffer.UV6Kind
  31379. * - BABYLON.VertexBuffer.ColorKind
  31380. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31382. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31384. *
  31385. * Returns the Mesh.
  31386. */
  31387. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31388. if (!this._geometry) {
  31389. return this;
  31390. }
  31391. if (!makeItUnique) {
  31392. this._geometry.updateVerticesData(kind, data, updateExtends);
  31393. }
  31394. else {
  31395. this.makeGeometryUnique();
  31396. this.updateVerticesData(kind, data, updateExtends, false);
  31397. }
  31398. return this;
  31399. };
  31400. /**
  31401. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31402. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31403. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31404. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31405. * Returns the Mesh.
  31406. */
  31407. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31408. if (computeNormals === void 0) { computeNormals = true; }
  31409. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31410. if (!positions) {
  31411. return this;
  31412. }
  31413. positionFunction(positions);
  31414. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31415. if (computeNormals) {
  31416. var indices = this.getIndices();
  31417. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31418. if (!normals) {
  31419. return this;
  31420. }
  31421. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31422. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31423. }
  31424. return this;
  31425. };
  31426. /**
  31427. * Creates a un-shared specific occurence of the geometry for the mesh.
  31428. * Returns the Mesh.
  31429. */
  31430. Mesh.prototype.makeGeometryUnique = function () {
  31431. if (!this._geometry) {
  31432. return this;
  31433. }
  31434. var oldGeometry = this._geometry;
  31435. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31436. oldGeometry.releaseForMesh(this, true);
  31437. geometry.applyToMesh(this);
  31438. return this;
  31439. };
  31440. /**
  31441. * Sets the mesh indices.
  31442. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31443. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31444. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31445. * This method creates a new index buffer each call.
  31446. * Returns the Mesh.
  31447. */
  31448. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31449. if (totalVertices === void 0) { totalVertices = null; }
  31450. if (updatable === void 0) { updatable = false; }
  31451. if (!this._geometry) {
  31452. var vertexData = new BABYLON.VertexData();
  31453. vertexData.indices = indices;
  31454. var scene = this.getScene();
  31455. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31456. }
  31457. else {
  31458. this._geometry.setIndices(indices, totalVertices, updatable);
  31459. }
  31460. return this;
  31461. };
  31462. /**
  31463. * Update the current index buffer
  31464. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31465. * Returns the Mesh.
  31466. */
  31467. Mesh.prototype.updateIndices = function (indices, offset) {
  31468. if (!this._geometry) {
  31469. return this;
  31470. }
  31471. this._geometry.updateIndices(indices, offset);
  31472. return this;
  31473. };
  31474. /**
  31475. * Invert the geometry to move from a right handed system to a left handed one.
  31476. * Returns the Mesh.
  31477. */
  31478. Mesh.prototype.toLeftHanded = function () {
  31479. if (!this._geometry) {
  31480. return this;
  31481. }
  31482. this._geometry.toLeftHanded();
  31483. return this;
  31484. };
  31485. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31486. if (!this._geometry) {
  31487. return this;
  31488. }
  31489. var engine = this.getScene().getEngine();
  31490. // Wireframe
  31491. var indexToBind;
  31492. if (this._unIndexed) {
  31493. indexToBind = null;
  31494. }
  31495. else {
  31496. switch (fillMode) {
  31497. case BABYLON.Material.PointFillMode:
  31498. indexToBind = null;
  31499. break;
  31500. case BABYLON.Material.WireFrameFillMode:
  31501. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31502. break;
  31503. default:
  31504. case BABYLON.Material.TriangleFillMode:
  31505. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31506. break;
  31507. }
  31508. }
  31509. // VBOs
  31510. this._geometry._bind(effect, indexToBind);
  31511. return this;
  31512. };
  31513. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31514. if (alternate === void 0) { alternate = false; }
  31515. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31516. return this;
  31517. }
  31518. this.onBeforeDrawObservable.notifyObservers(this);
  31519. var scene = this.getScene();
  31520. var engine = scene.getEngine();
  31521. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31522. // or triangles as points
  31523. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31524. }
  31525. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31526. // Triangles as wireframe
  31527. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31528. }
  31529. else {
  31530. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31531. }
  31532. if (scene._isAlternateRenderingEnabled && !alternate) {
  31533. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31534. if (!effect || !scene.activeCamera) {
  31535. return this;
  31536. }
  31537. scene._switchToAlternateCameraConfiguration(true);
  31538. this._effectiveMaterial.bindView(effect);
  31539. this._effectiveMaterial.bindViewProjection(effect);
  31540. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31541. this._draw(subMesh, fillMode, instancesCount, true);
  31542. engine.setViewport(scene.activeCamera.viewport);
  31543. scene._switchToAlternateCameraConfiguration(false);
  31544. this._effectiveMaterial.bindView(effect);
  31545. this._effectiveMaterial.bindViewProjection(effect);
  31546. }
  31547. return this;
  31548. };
  31549. /**
  31550. * Registers for this mesh a javascript function called just before the rendering process.
  31551. * This function is passed the current mesh.
  31552. * Return the Mesh.
  31553. */
  31554. Mesh.prototype.registerBeforeRender = function (func) {
  31555. this.onBeforeRenderObservable.add(func);
  31556. return this;
  31557. };
  31558. /**
  31559. * Disposes a previously registered javascript function called before the rendering.
  31560. * This function is passed the current mesh.
  31561. * Returns the Mesh.
  31562. */
  31563. Mesh.prototype.unregisterBeforeRender = function (func) {
  31564. this.onBeforeRenderObservable.removeCallback(func);
  31565. return this;
  31566. };
  31567. /**
  31568. * Registers for this mesh a javascript function called just after the rendering is complete.
  31569. * This function is passed the current mesh.
  31570. * Returns the Mesh.
  31571. */
  31572. Mesh.prototype.registerAfterRender = function (func) {
  31573. this.onAfterRenderObservable.add(func);
  31574. return this;
  31575. };
  31576. /**
  31577. * Disposes a previously registered javascript function called after the rendering.
  31578. * This function is passed the current mesh.
  31579. * Return the Mesh.
  31580. */
  31581. Mesh.prototype.unregisterAfterRender = function (func) {
  31582. this.onAfterRenderObservable.removeCallback(func);
  31583. return this;
  31584. };
  31585. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31586. var scene = this.getScene();
  31587. this._batchCache.mustReturn = false;
  31588. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31589. this._batchCache.visibleInstances[subMeshId] = null;
  31590. if (this._visibleInstances) {
  31591. var currentRenderId = scene.getRenderId();
  31592. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31593. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31594. var selfRenderId = this._renderId;
  31595. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31596. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31597. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31598. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31599. }
  31600. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31601. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31602. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31603. this._batchCache.mustReturn = true;
  31604. return this._batchCache;
  31605. }
  31606. if (currentRenderId !== selfRenderId) {
  31607. this._batchCache.renderSelf[subMeshId] = false;
  31608. }
  31609. }
  31610. this._renderIdForInstances[subMeshId] = currentRenderId;
  31611. }
  31612. return this._batchCache;
  31613. };
  31614. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31615. var visibleInstances = batch.visibleInstances[subMesh._id];
  31616. if (!visibleInstances) {
  31617. return this;
  31618. }
  31619. var matricesCount = visibleInstances.length + 1;
  31620. var bufferSize = matricesCount * 16 * 4;
  31621. var currentInstancesBufferSize = this._instancesBufferSize;
  31622. var instancesBuffer = this._instancesBuffer;
  31623. while (this._instancesBufferSize < bufferSize) {
  31624. this._instancesBufferSize *= 2;
  31625. }
  31626. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31627. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31628. }
  31629. var offset = 0;
  31630. var instancesCount = 0;
  31631. var world = this.getWorldMatrix();
  31632. if (batch.renderSelf[subMesh._id]) {
  31633. world.copyToArray(this._instancesData, offset);
  31634. offset += 16;
  31635. instancesCount++;
  31636. }
  31637. if (visibleInstances) {
  31638. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31639. var instance = visibleInstances[instanceIndex];
  31640. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31641. offset += 16;
  31642. instancesCount++;
  31643. }
  31644. }
  31645. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31646. if (instancesBuffer) {
  31647. instancesBuffer.dispose();
  31648. }
  31649. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31650. this._instancesBuffer = instancesBuffer;
  31651. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31652. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31653. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31654. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31655. }
  31656. else {
  31657. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31658. }
  31659. this._bind(subMesh, effect, fillMode);
  31660. this._draw(subMesh, fillMode, instancesCount);
  31661. engine.unbindInstanceAttributes();
  31662. return this;
  31663. };
  31664. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31665. var scene = this.getScene();
  31666. var engine = scene.getEngine();
  31667. if (hardwareInstancedRendering) {
  31668. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31669. }
  31670. else {
  31671. if (batch.renderSelf[subMesh._id]) {
  31672. // Draw
  31673. if (onBeforeDraw) {
  31674. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31675. }
  31676. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31677. }
  31678. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31679. if (visibleInstancesForSubMesh) {
  31680. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31681. var instance = visibleInstancesForSubMesh[instanceIndex];
  31682. // World
  31683. var world = instance.getWorldMatrix();
  31684. if (onBeforeDraw) {
  31685. onBeforeDraw(true, world, effectiveMaterial);
  31686. }
  31687. // Draw
  31688. this._draw(subMesh, fillMode);
  31689. }
  31690. }
  31691. }
  31692. return this;
  31693. };
  31694. /**
  31695. * Triggers the draw call for the mesh.
  31696. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31697. * Returns the Mesh.
  31698. */
  31699. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31700. this.checkOcclusionQuery();
  31701. if (this._isOccluded) {
  31702. return this;
  31703. }
  31704. var scene = this.getScene();
  31705. // Managing instances
  31706. var batch = this._getInstancesRenderList(subMesh._id);
  31707. if (batch.mustReturn) {
  31708. return this;
  31709. }
  31710. // Checking geometry state
  31711. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31712. return this;
  31713. }
  31714. this.onBeforeRenderObservable.notifyObservers(this);
  31715. var engine = scene.getEngine();
  31716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31717. // Material
  31718. var material = subMesh.getMaterial();
  31719. if (!material) {
  31720. return this;
  31721. }
  31722. this._effectiveMaterial = material;
  31723. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31724. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31725. return this;
  31726. }
  31727. }
  31728. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31729. return this;
  31730. }
  31731. // Alpha mode
  31732. if (enableAlphaMode) {
  31733. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31734. }
  31735. // Outline - step 1
  31736. var savedDepthWrite = engine.getDepthWrite();
  31737. if (this.renderOutline) {
  31738. engine.setDepthWrite(false);
  31739. scene.getOutlineRenderer().render(subMesh, batch);
  31740. engine.setDepthWrite(savedDepthWrite);
  31741. }
  31742. var effect;
  31743. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31744. effect = subMesh.effect;
  31745. }
  31746. else {
  31747. effect = this._effectiveMaterial.getEffect();
  31748. }
  31749. if (!effect) {
  31750. return this;
  31751. }
  31752. var sideOrientation = this.overrideMaterialSideOrientation;
  31753. if (sideOrientation == null) {
  31754. sideOrientation = this._effectiveMaterial.sideOrientation;
  31755. if (this._getWorldMatrixDeterminant() < 0) {
  31756. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31757. }
  31758. }
  31759. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31760. if (this._effectiveMaterial.forceDepthWrite) {
  31761. engine.setDepthWrite(true);
  31762. }
  31763. // Bind
  31764. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31765. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31766. this._bind(subMesh, effect, fillMode);
  31767. }
  31768. var world = this.getWorldMatrix();
  31769. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31770. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31771. }
  31772. else {
  31773. this._effectiveMaterial.bind(world, this);
  31774. }
  31775. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31776. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31777. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31778. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31779. }
  31780. // Draw
  31781. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31782. // Unbind
  31783. this._effectiveMaterial.unbind();
  31784. // Outline - step 2
  31785. if (this.renderOutline && savedDepthWrite) {
  31786. engine.setDepthWrite(true);
  31787. engine.setColorWrite(false);
  31788. scene.getOutlineRenderer().render(subMesh, batch);
  31789. engine.setColorWrite(true);
  31790. }
  31791. // Overlay
  31792. if (this.renderOverlay) {
  31793. var currentMode = engine.getAlphaMode();
  31794. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31795. scene.getOutlineRenderer().render(subMesh, batch, true);
  31796. engine.setAlphaMode(currentMode);
  31797. }
  31798. this.onAfterRenderObservable.notifyObservers(this);
  31799. return this;
  31800. };
  31801. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31802. if (isInstance && effectiveMaterial) {
  31803. effectiveMaterial.bindOnlyWorldMatrix(world);
  31804. }
  31805. };
  31806. /**
  31807. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31808. */
  31809. Mesh.prototype.getEmittedParticleSystems = function () {
  31810. var results = new Array();
  31811. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31812. var particleSystem = this.getScene().particleSystems[index];
  31813. if (particleSystem.emitter === this) {
  31814. results.push(particleSystem);
  31815. }
  31816. }
  31817. return results;
  31818. };
  31819. /**
  31820. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31821. */
  31822. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31823. var results = new Array();
  31824. var descendants = this.getDescendants();
  31825. descendants.push(this);
  31826. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31827. var particleSystem = this.getScene().particleSystems[index];
  31828. var emitter = particleSystem.emitter;
  31829. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31830. results.push(particleSystem);
  31831. }
  31832. }
  31833. return results;
  31834. };
  31835. Mesh.prototype._checkDelayState = function () {
  31836. var scene = this.getScene();
  31837. if (this._geometry) {
  31838. this._geometry.load(scene);
  31839. }
  31840. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31842. this._queueLoad(scene);
  31843. }
  31844. return this;
  31845. };
  31846. Mesh.prototype._queueLoad = function (scene) {
  31847. var _this = this;
  31848. scene._addPendingData(this);
  31849. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31850. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31851. if (data instanceof ArrayBuffer) {
  31852. _this._delayLoadingFunction(data, _this);
  31853. }
  31854. else {
  31855. _this._delayLoadingFunction(JSON.parse(data), _this);
  31856. }
  31857. _this.instances.forEach(function (instance) {
  31858. instance._syncSubMeshes();
  31859. });
  31860. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31861. scene._removePendingData(_this);
  31862. }, function () { }, scene.database, getBinaryData);
  31863. return this;
  31864. };
  31865. /**
  31866. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31867. */
  31868. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31869. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31870. return false;
  31871. }
  31872. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31873. return false;
  31874. }
  31875. this._checkDelayState();
  31876. return true;
  31877. };
  31878. /**
  31879. * Sets the mesh material by the material or multiMaterial `id` property.
  31880. * The material `id` is a string identifying the material or the multiMaterial.
  31881. * This method returns the Mesh.
  31882. */
  31883. Mesh.prototype.setMaterialByID = function (id) {
  31884. var materials = this.getScene().materials;
  31885. var index;
  31886. for (index = materials.length - 1; index > -1; index--) {
  31887. if (materials[index].id === id) {
  31888. this.material = materials[index];
  31889. return this;
  31890. }
  31891. }
  31892. // Multi
  31893. var multiMaterials = this.getScene().multiMaterials;
  31894. for (index = multiMaterials.length - 1; index > -1; index--) {
  31895. if (multiMaterials[index].id === id) {
  31896. this.material = multiMaterials[index];
  31897. return this;
  31898. }
  31899. }
  31900. return this;
  31901. };
  31902. /**
  31903. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31904. */
  31905. Mesh.prototype.getAnimatables = function () {
  31906. var results = new Array();
  31907. if (this.material) {
  31908. results.push(this.material);
  31909. }
  31910. if (this.skeleton) {
  31911. results.push(this.skeleton);
  31912. }
  31913. return results;
  31914. };
  31915. /**
  31916. * Modifies the mesh geometry according to the passed transformation matrix.
  31917. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31918. * The mesh normals are modified accordingly the same transformation.
  31919. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31920. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31921. * Returns the Mesh.
  31922. */
  31923. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31924. // Position
  31925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31926. return this;
  31927. }
  31928. var submeshes = this.subMeshes.splice(0);
  31929. this._resetPointsArrayCache();
  31930. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31931. var temp = new Array();
  31932. var index;
  31933. for (index = 0; index < data.length; index += 3) {
  31934. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31935. }
  31936. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31937. // Normals
  31938. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31939. return this;
  31940. }
  31941. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31942. temp = [];
  31943. for (index = 0; index < data.length; index += 3) {
  31944. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31945. }
  31946. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31947. // flip faces?
  31948. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31949. this.flipFaces();
  31950. }
  31951. // Restore submeshes
  31952. this.releaseSubMeshes();
  31953. this.subMeshes = submeshes;
  31954. return this;
  31955. };
  31956. /**
  31957. * Modifies the mesh geometry according to its own current World Matrix.
  31958. * The mesh World Matrix is then reset.
  31959. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31960. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31961. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31962. * Returns the Mesh.
  31963. */
  31964. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31965. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31966. this.scaling.copyFromFloats(1, 1, 1);
  31967. this.position.copyFromFloats(0, 0, 0);
  31968. this.rotation.copyFromFloats(0, 0, 0);
  31969. //only if quaternion is already set
  31970. if (this.rotationQuaternion) {
  31971. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31972. }
  31973. this._worldMatrix = BABYLON.Matrix.Identity();
  31974. return this;
  31975. };
  31976. Object.defineProperty(Mesh.prototype, "_positions", {
  31977. // Cache
  31978. get: function () {
  31979. if (this._geometry) {
  31980. return this._geometry._positions;
  31981. }
  31982. return null;
  31983. },
  31984. enumerable: true,
  31985. configurable: true
  31986. });
  31987. Mesh.prototype._resetPointsArrayCache = function () {
  31988. if (this._geometry) {
  31989. this._geometry._resetPointsArrayCache();
  31990. }
  31991. return this;
  31992. };
  31993. Mesh.prototype._generatePointsArray = function () {
  31994. if (this._geometry) {
  31995. return this._geometry._generatePointsArray();
  31996. }
  31997. return false;
  31998. };
  31999. /**
  32000. * Returns a new Mesh object generated from the current mesh properties.
  32001. * This method must not get confused with createInstance().
  32002. * The parameter `name` is a string, the name given to the new mesh.
  32003. * The optional parameter `newParent` can be any Node object (default `null`).
  32004. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32005. * 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.
  32006. */
  32007. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32008. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32009. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32010. };
  32011. /**
  32012. * Releases resources associated with this mesh.
  32013. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32014. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32015. */
  32016. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32017. var _this = this;
  32018. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32019. this.morphTargetManager = null;
  32020. if (this._geometry) {
  32021. this._geometry.releaseForMesh(this, true);
  32022. }
  32023. // Sources
  32024. var meshes = this.getScene().meshes;
  32025. meshes.forEach(function (abstractMesh) {
  32026. var mesh = abstractMesh;
  32027. if (mesh._source && mesh._source === _this) {
  32028. mesh._source = null;
  32029. }
  32030. });
  32031. this._source = null;
  32032. // Instances
  32033. if (this._instancesBuffer) {
  32034. this._instancesBuffer.dispose();
  32035. this._instancesBuffer = null;
  32036. }
  32037. while (this.instances.length) {
  32038. this.instances[0].dispose();
  32039. }
  32040. // Effect layers.
  32041. var effectLayers = this.getScene().effectLayers;
  32042. for (var i = 0; i < effectLayers.length; i++) {
  32043. var effectLayer = effectLayers[i];
  32044. if (effectLayer) {
  32045. effectLayer._disposeMesh(this);
  32046. }
  32047. }
  32048. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32049. };
  32050. /**
  32051. * Modifies the mesh geometry according to a displacement map.
  32052. * 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.
  32053. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32054. * This method returns nothing.
  32055. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32056. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32057. * 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.
  32058. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32059. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32060. *
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32064. var _this = this;
  32065. var scene = this.getScene();
  32066. var onload = function (img) {
  32067. // Getting height map data
  32068. var canvas = document.createElement("canvas");
  32069. var context = canvas.getContext("2d");
  32070. var heightMapWidth = img.width;
  32071. var heightMapHeight = img.height;
  32072. canvas.width = heightMapWidth;
  32073. canvas.height = heightMapHeight;
  32074. context.drawImage(img, 0, 0);
  32075. // Create VertexData from map data
  32076. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32077. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32078. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32079. //execute success callback, if set
  32080. if (onSuccess) {
  32081. onSuccess(_this);
  32082. }
  32083. };
  32084. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32085. return this;
  32086. };
  32087. /**
  32088. * Modifies the mesh geometry according to a displacementMap buffer.
  32089. * 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.
  32090. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32091. * This method returns nothing.
  32092. * 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.
  32093. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32094. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32095. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32096. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32097. *
  32098. * Returns the Mesh.
  32099. */
  32100. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32101. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32102. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32103. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32104. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32105. return this;
  32106. }
  32107. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32108. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32109. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32110. var position = BABYLON.Vector3.Zero();
  32111. var normal = BABYLON.Vector3.Zero();
  32112. var uv = BABYLON.Vector2.Zero();
  32113. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32114. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32115. for (var index = 0; index < positions.length; index += 3) {
  32116. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32117. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32118. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32119. // Compute height
  32120. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32121. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32122. var pos = (u + v * heightMapWidth) * 4;
  32123. var r = buffer[pos] / 255.0;
  32124. var g = buffer[pos + 1] / 255.0;
  32125. var b = buffer[pos + 2] / 255.0;
  32126. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32127. normal.normalize();
  32128. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32129. position = position.add(normal);
  32130. position.toArray(positions, index);
  32131. }
  32132. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32133. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32134. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32135. return this;
  32136. };
  32137. /**
  32138. * Modify the mesh to get a flat shading rendering.
  32139. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32140. * This method returns the Mesh.
  32141. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32142. */
  32143. Mesh.prototype.convertToFlatShadedMesh = function () {
  32144. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32145. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32146. var kinds = this.getVerticesDataKinds();
  32147. var vbs = {};
  32148. var data = {};
  32149. var newdata = {};
  32150. var updatableNormals = false;
  32151. var kindIndex;
  32152. var kind;
  32153. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32154. kind = kinds[kindIndex];
  32155. var vertexBuffer = this.getVertexBuffer(kind);
  32156. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32157. updatableNormals = vertexBuffer.isUpdatable();
  32158. kinds.splice(kindIndex, 1);
  32159. kindIndex--;
  32160. continue;
  32161. }
  32162. vbs[kind] = vertexBuffer;
  32163. data[kind] = vbs[kind].getData();
  32164. newdata[kind] = [];
  32165. }
  32166. // Save previous submeshes
  32167. var previousSubmeshes = this.subMeshes.slice(0);
  32168. var indices = this.getIndices();
  32169. var totalIndices = this.getTotalIndices();
  32170. // Generating unique vertices per face
  32171. var index;
  32172. for (index = 0; index < totalIndices; index++) {
  32173. var vertexIndex = indices[index];
  32174. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32175. kind = kinds[kindIndex];
  32176. var stride = vbs[kind].getStrideSize();
  32177. for (var offset = 0; offset < stride; offset++) {
  32178. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32179. }
  32180. }
  32181. }
  32182. // Updating faces & normal
  32183. var normals = [];
  32184. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32185. for (index = 0; index < totalIndices; index += 3) {
  32186. indices[index] = index;
  32187. indices[index + 1] = index + 1;
  32188. indices[index + 2] = index + 2;
  32189. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32190. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32191. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32192. var p1p2 = p1.subtract(p2);
  32193. var p3p2 = p3.subtract(p2);
  32194. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32195. // Store same normals for every vertex
  32196. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32197. normals.push(normal.x);
  32198. normals.push(normal.y);
  32199. normals.push(normal.z);
  32200. }
  32201. }
  32202. this.setIndices(indices);
  32203. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32204. // Updating vertex buffers
  32205. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32206. kind = kinds[kindIndex];
  32207. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32208. }
  32209. // Updating submeshes
  32210. this.releaseSubMeshes();
  32211. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32212. var previousOne = previousSubmeshes[submeshIndex];
  32213. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32214. }
  32215. this.synchronizeInstances();
  32216. return this;
  32217. };
  32218. /**
  32219. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32220. * In other words, more vertices, no more indices and a single bigger VBO.
  32221. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32222. * Returns the Mesh.
  32223. */
  32224. Mesh.prototype.convertToUnIndexedMesh = function () {
  32225. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32226. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32227. var kinds = this.getVerticesDataKinds();
  32228. var vbs = {};
  32229. var data = {};
  32230. var newdata = {};
  32231. var kindIndex;
  32232. var kind;
  32233. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32234. kind = kinds[kindIndex];
  32235. var vertexBuffer = this.getVertexBuffer(kind);
  32236. vbs[kind] = vertexBuffer;
  32237. data[kind] = vbs[kind].getData();
  32238. newdata[kind] = [];
  32239. }
  32240. // Save previous submeshes
  32241. var previousSubmeshes = this.subMeshes.slice(0);
  32242. var indices = this.getIndices();
  32243. var totalIndices = this.getTotalIndices();
  32244. // Generating unique vertices per face
  32245. var index;
  32246. for (index = 0; index < totalIndices; index++) {
  32247. var vertexIndex = indices[index];
  32248. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32249. kind = kinds[kindIndex];
  32250. var stride = vbs[kind].getStrideSize();
  32251. for (var offset = 0; offset < stride; offset++) {
  32252. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32253. }
  32254. }
  32255. }
  32256. // Updating indices
  32257. for (index = 0; index < totalIndices; index += 3) {
  32258. indices[index] = index;
  32259. indices[index + 1] = index + 1;
  32260. indices[index + 2] = index + 2;
  32261. }
  32262. this.setIndices(indices);
  32263. // Updating vertex buffers
  32264. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32265. kind = kinds[kindIndex];
  32266. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32267. }
  32268. // Updating submeshes
  32269. this.releaseSubMeshes();
  32270. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32271. var previousOne = previousSubmeshes[submeshIndex];
  32272. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32273. }
  32274. this._unIndexed = true;
  32275. this.synchronizeInstances();
  32276. return this;
  32277. };
  32278. /**
  32279. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32280. * This method returns the Mesh.
  32281. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32282. */
  32283. Mesh.prototype.flipFaces = function (flipNormals) {
  32284. if (flipNormals === void 0) { flipNormals = false; }
  32285. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32286. var i;
  32287. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32288. for (i = 0; i < vertex_data.normals.length; i++) {
  32289. vertex_data.normals[i] *= -1;
  32290. }
  32291. }
  32292. if (vertex_data.indices) {
  32293. var temp;
  32294. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32295. // reassign indices
  32296. temp = vertex_data.indices[i + 1];
  32297. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32298. vertex_data.indices[i + 2] = temp;
  32299. }
  32300. }
  32301. vertex_data.applyToMesh(this);
  32302. return this;
  32303. };
  32304. // Instances
  32305. /**
  32306. * Creates a new InstancedMesh object from the mesh model.
  32307. * An instance shares the same properties and the same material than its model.
  32308. * Only these properties of each instance can then be set individually :
  32309. * - position
  32310. * - rotation
  32311. * - rotationQuaternion
  32312. * - setPivotMatrix
  32313. * - scaling
  32314. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32315. * Warning : this method is not supported for Line mesh and LineSystem
  32316. */
  32317. Mesh.prototype.createInstance = function (name) {
  32318. return new BABYLON.InstancedMesh(name, this);
  32319. };
  32320. /**
  32321. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32322. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32323. * This method returns the Mesh.
  32324. */
  32325. Mesh.prototype.synchronizeInstances = function () {
  32326. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32327. var instance = this.instances[instanceIndex];
  32328. instance._syncSubMeshes();
  32329. }
  32330. return this;
  32331. };
  32332. /**
  32333. * Simplify the mesh according to the given array of settings.
  32334. * Function will return immediately and will simplify async. It returns the Mesh.
  32335. * @param settings a collection of simplification settings.
  32336. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32337. * @param type the type of simplification to run.
  32338. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32339. */
  32340. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32341. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32342. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32343. this.getScene().simplificationQueue.addTask({
  32344. settings: settings,
  32345. parallelProcessing: parallelProcessing,
  32346. mesh: this,
  32347. simplificationType: simplificationType,
  32348. successCallback: successCallback
  32349. });
  32350. return this;
  32351. };
  32352. /**
  32353. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32354. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32355. * This should be used together with the simplification to avoid disappearing triangles.
  32356. * Returns the Mesh.
  32357. * @param successCallback an optional success callback to be called after the optimization finished.
  32358. */
  32359. Mesh.prototype.optimizeIndices = function (successCallback) {
  32360. var _this = this;
  32361. var indices = this.getIndices();
  32362. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32363. if (!positions || !indices) {
  32364. return this;
  32365. }
  32366. var vectorPositions = new Array();
  32367. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32368. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32369. }
  32370. var dupes = new Array();
  32371. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32372. var realPos = vectorPositions.length - 1 - iteration;
  32373. var testedPosition = vectorPositions[realPos];
  32374. for (var j = 0; j < realPos; ++j) {
  32375. var againstPosition = vectorPositions[j];
  32376. if (testedPosition.equals(againstPosition)) {
  32377. dupes[realPos] = j;
  32378. break;
  32379. }
  32380. }
  32381. }, function () {
  32382. for (var i = 0; i < indices.length; ++i) {
  32383. indices[i] = dupes[indices[i]] || indices[i];
  32384. }
  32385. //indices are now reordered
  32386. var originalSubMeshes = _this.subMeshes.slice(0);
  32387. _this.setIndices(indices);
  32388. _this.subMeshes = originalSubMeshes;
  32389. if (successCallback) {
  32390. successCallback(_this);
  32391. }
  32392. });
  32393. return this;
  32394. };
  32395. Mesh.prototype.serialize = function (serializationObject) {
  32396. serializationObject.name = this.name;
  32397. serializationObject.id = this.id;
  32398. serializationObject.type = this.getClassName();
  32399. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32400. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32401. }
  32402. serializationObject.position = this.position.asArray();
  32403. if (this.rotationQuaternion) {
  32404. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32405. }
  32406. else if (this.rotation) {
  32407. serializationObject.rotation = this.rotation.asArray();
  32408. }
  32409. serializationObject.scaling = this.scaling.asArray();
  32410. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32411. serializationObject.isEnabled = this.isEnabled(false);
  32412. serializationObject.isVisible = this.isVisible;
  32413. serializationObject.infiniteDistance = this.infiniteDistance;
  32414. serializationObject.pickable = this.isPickable;
  32415. serializationObject.receiveShadows = this.receiveShadows;
  32416. serializationObject.billboardMode = this.billboardMode;
  32417. serializationObject.visibility = this.visibility;
  32418. serializationObject.checkCollisions = this.checkCollisions;
  32419. serializationObject.isBlocker = this.isBlocker;
  32420. // Parent
  32421. if (this.parent) {
  32422. serializationObject.parentId = this.parent.id;
  32423. }
  32424. // Geometry
  32425. serializationObject.isUnIndexed = this.isUnIndexed;
  32426. var geometry = this._geometry;
  32427. if (geometry) {
  32428. var geometryId = geometry.id;
  32429. serializationObject.geometryId = geometryId;
  32430. // SubMeshes
  32431. serializationObject.subMeshes = [];
  32432. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32433. var subMesh = this.subMeshes[subIndex];
  32434. serializationObject.subMeshes.push({
  32435. materialIndex: subMesh.materialIndex,
  32436. verticesStart: subMesh.verticesStart,
  32437. verticesCount: subMesh.verticesCount,
  32438. indexStart: subMesh.indexStart,
  32439. indexCount: subMesh.indexCount
  32440. });
  32441. }
  32442. }
  32443. // Material
  32444. if (this.material) {
  32445. serializationObject.materialId = this.material.id;
  32446. }
  32447. else {
  32448. this.material = null;
  32449. }
  32450. // Morph targets
  32451. if (this.morphTargetManager) {
  32452. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32453. }
  32454. // Skeleton
  32455. if (this.skeleton) {
  32456. serializationObject.skeletonId = this.skeleton.id;
  32457. }
  32458. // Physics
  32459. //TODO implement correct serialization for physics impostors.
  32460. var impostor = this.getPhysicsImpostor();
  32461. if (impostor) {
  32462. serializationObject.physicsMass = impostor.getParam("mass");
  32463. serializationObject.physicsFriction = impostor.getParam("friction");
  32464. serializationObject.physicsRestitution = impostor.getParam("mass");
  32465. serializationObject.physicsImpostor = impostor.type;
  32466. }
  32467. // Metadata
  32468. if (this.metadata) {
  32469. serializationObject.metadata = this.metadata;
  32470. }
  32471. // Instances
  32472. serializationObject.instances = [];
  32473. for (var index = 0; index < this.instances.length; index++) {
  32474. var instance = this.instances[index];
  32475. var serializationInstance = {
  32476. name: instance.name,
  32477. id: instance.id,
  32478. position: instance.position.asArray(),
  32479. scaling: instance.scaling.asArray()
  32480. };
  32481. if (instance.rotationQuaternion) {
  32482. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32483. }
  32484. else if (instance.rotation) {
  32485. serializationInstance.rotation = instance.rotation.asArray();
  32486. }
  32487. serializationObject.instances.push(serializationInstance);
  32488. // Animations
  32489. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32490. serializationInstance.ranges = instance.serializeAnimationRanges();
  32491. }
  32492. //
  32493. // Animations
  32494. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32495. serializationObject.ranges = this.serializeAnimationRanges();
  32496. // Layer mask
  32497. serializationObject.layerMask = this.layerMask;
  32498. // Alpha
  32499. serializationObject.alphaIndex = this.alphaIndex;
  32500. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32501. // Overlay
  32502. serializationObject.overlayAlpha = this.overlayAlpha;
  32503. serializationObject.overlayColor = this.overlayColor.asArray();
  32504. serializationObject.renderOverlay = this.renderOverlay;
  32505. // Fog
  32506. serializationObject.applyFog = this.applyFog;
  32507. // Action Manager
  32508. if (this.actionManager) {
  32509. serializationObject.actions = this.actionManager.serialize(this.name);
  32510. }
  32511. };
  32512. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32513. if (!this.geometry) {
  32514. return;
  32515. }
  32516. this._markSubMeshesAsAttributesDirty();
  32517. var morphTargetManager = this._morphTargetManager;
  32518. if (morphTargetManager && morphTargetManager.vertexCount) {
  32519. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32520. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32521. this.morphTargetManager = null;
  32522. return;
  32523. }
  32524. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32525. var morphTarget = morphTargetManager.getActiveTarget(index);
  32526. var positions = morphTarget.getPositions();
  32527. if (!positions) {
  32528. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32529. return;
  32530. }
  32531. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32532. var normals = morphTarget.getNormals();
  32533. if (normals) {
  32534. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32535. }
  32536. var tangents = morphTarget.getTangents();
  32537. if (tangents) {
  32538. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32539. }
  32540. }
  32541. }
  32542. else {
  32543. var index = 0;
  32544. // Positions
  32545. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32546. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32547. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32548. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32549. }
  32550. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32551. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32552. }
  32553. index++;
  32554. }
  32555. }
  32556. };
  32557. // Statics
  32558. /**
  32559. * Returns a new Mesh object parsed from the source provided.
  32560. * The parameter `parsedMesh` is the source.
  32561. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32562. */
  32563. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32564. var mesh;
  32565. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32566. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32567. }
  32568. else {
  32569. mesh = new Mesh(parsedMesh.name, scene);
  32570. }
  32571. mesh.id = parsedMesh.id;
  32572. if (BABYLON.Tags) {
  32573. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32574. }
  32575. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32576. if (parsedMesh.metadata !== undefined) {
  32577. mesh.metadata = parsedMesh.metadata;
  32578. }
  32579. if (parsedMesh.rotationQuaternion) {
  32580. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32581. }
  32582. else if (parsedMesh.rotation) {
  32583. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32584. }
  32585. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32586. if (parsedMesh.localMatrix) {
  32587. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32588. }
  32589. else if (parsedMesh.pivotMatrix) {
  32590. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32591. }
  32592. mesh.setEnabled(parsedMesh.isEnabled);
  32593. mesh.isVisible = parsedMesh.isVisible;
  32594. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32595. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32596. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32597. if (parsedMesh.applyFog !== undefined) {
  32598. mesh.applyFog = parsedMesh.applyFog;
  32599. }
  32600. if (parsedMesh.pickable !== undefined) {
  32601. mesh.isPickable = parsedMesh.pickable;
  32602. }
  32603. if (parsedMesh.alphaIndex !== undefined) {
  32604. mesh.alphaIndex = parsedMesh.alphaIndex;
  32605. }
  32606. mesh.receiveShadows = parsedMesh.receiveShadows;
  32607. mesh.billboardMode = parsedMesh.billboardMode;
  32608. if (parsedMesh.visibility !== undefined) {
  32609. mesh.visibility = parsedMesh.visibility;
  32610. }
  32611. mesh.checkCollisions = parsedMesh.checkCollisions;
  32612. if (parsedMesh.isBlocker !== undefined) {
  32613. mesh.isBlocker = parsedMesh.isBlocker;
  32614. }
  32615. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32616. // freezeWorldMatrix
  32617. if (parsedMesh.freezeWorldMatrix) {
  32618. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32619. }
  32620. // Parent
  32621. if (parsedMesh.parentId) {
  32622. mesh._waitingParentId = parsedMesh.parentId;
  32623. }
  32624. // Actions
  32625. if (parsedMesh.actions !== undefined) {
  32626. mesh._waitingActions = parsedMesh.actions;
  32627. }
  32628. // Overlay
  32629. if (parsedMesh.overlayAlpha !== undefined) {
  32630. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32631. }
  32632. if (parsedMesh.overlayColor !== undefined) {
  32633. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32634. }
  32635. if (parsedMesh.renderOverlay !== undefined) {
  32636. mesh.renderOverlay = parsedMesh.renderOverlay;
  32637. }
  32638. // Geometry
  32639. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32640. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32641. if (parsedMesh.delayLoadingFile) {
  32642. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32643. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32644. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32645. if (parsedMesh._binaryInfo) {
  32646. mesh._binaryInfo = parsedMesh._binaryInfo;
  32647. }
  32648. mesh._delayInfo = [];
  32649. if (parsedMesh.hasUVs) {
  32650. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32651. }
  32652. if (parsedMesh.hasUVs2) {
  32653. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32654. }
  32655. if (parsedMesh.hasUVs3) {
  32656. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32657. }
  32658. if (parsedMesh.hasUVs4) {
  32659. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32660. }
  32661. if (parsedMesh.hasUVs5) {
  32662. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32663. }
  32664. if (parsedMesh.hasUVs6) {
  32665. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32666. }
  32667. if (parsedMesh.hasColors) {
  32668. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32669. }
  32670. if (parsedMesh.hasMatricesIndices) {
  32671. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32672. }
  32673. if (parsedMesh.hasMatricesWeights) {
  32674. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32675. }
  32676. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32677. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32678. mesh._checkDelayState();
  32679. }
  32680. }
  32681. else {
  32682. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32683. }
  32684. // Material
  32685. if (parsedMesh.materialId) {
  32686. mesh.setMaterialByID(parsedMesh.materialId);
  32687. }
  32688. else {
  32689. mesh.material = null;
  32690. }
  32691. // Morph targets
  32692. if (parsedMesh.morphTargetManagerId > -1) {
  32693. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32694. }
  32695. // Skeleton
  32696. if (parsedMesh.skeletonId > -1) {
  32697. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32698. if (parsedMesh.numBoneInfluencers) {
  32699. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32700. }
  32701. }
  32702. // Animations
  32703. if (parsedMesh.animations) {
  32704. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32705. var parsedAnimation = parsedMesh.animations[animationIndex];
  32706. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32707. }
  32708. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32709. }
  32710. if (parsedMesh.autoAnimate) {
  32711. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32712. }
  32713. // Layer Mask
  32714. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32715. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32716. }
  32717. else {
  32718. mesh.layerMask = 0x0FFFFFFF;
  32719. }
  32720. // Physics
  32721. if (parsedMesh.physicsImpostor) {
  32722. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32723. mass: parsedMesh.physicsMass,
  32724. friction: parsedMesh.physicsFriction,
  32725. restitution: parsedMesh.physicsRestitution
  32726. }, scene);
  32727. }
  32728. // Instances
  32729. if (parsedMesh.instances) {
  32730. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32731. var parsedInstance = parsedMesh.instances[index];
  32732. var instance = mesh.createInstance(parsedInstance.name);
  32733. if (parsedInstance.id) {
  32734. instance.id = parsedInstance.id;
  32735. }
  32736. if (BABYLON.Tags) {
  32737. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32738. }
  32739. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32740. if (parsedInstance.parentId) {
  32741. instance._waitingParentId = parsedInstance.parentId;
  32742. }
  32743. if (parsedInstance.rotationQuaternion) {
  32744. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32745. }
  32746. else if (parsedInstance.rotation) {
  32747. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32748. }
  32749. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32750. instance.checkCollisions = mesh.checkCollisions;
  32751. if (parsedMesh.animations) {
  32752. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32753. parsedAnimation = parsedMesh.animations[animationIndex];
  32754. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32755. }
  32756. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32757. }
  32758. }
  32759. }
  32760. return mesh;
  32761. };
  32762. /**
  32763. * Creates a ribbon mesh.
  32764. * Please consider using the same method from the MeshBuilder class instead.
  32765. * 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.
  32766. *
  32767. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32768. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32769. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32770. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32771. * 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.
  32772. * 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.
  32773. * 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
  32774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32777. */
  32778. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32779. if (closeArray === void 0) { closeArray = false; }
  32780. if (updatable === void 0) { updatable = false; }
  32781. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32782. pathArray: pathArray,
  32783. closeArray: closeArray,
  32784. closePath: closePath,
  32785. offset: offset,
  32786. updatable: updatable,
  32787. sideOrientation: sideOrientation,
  32788. instance: instance
  32789. }, scene);
  32790. };
  32791. /**
  32792. * Creates a plane polygonal mesh. By default, this is a disc.
  32793. * Please consider using the same method from the MeshBuilder class instead.
  32794. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32795. * 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.
  32796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32799. */
  32800. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32801. if (scene === void 0) { scene = null; }
  32802. var options = {
  32803. radius: radius,
  32804. tessellation: tessellation,
  32805. sideOrientation: sideOrientation,
  32806. updatable: updatable
  32807. };
  32808. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32809. };
  32810. /**
  32811. * Creates a box mesh.
  32812. * Please consider using the same method from the MeshBuilder class instead.
  32813. * The parameter `size` sets the size (float) of each box side (default 1).
  32814. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32815. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32817. */
  32818. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32819. if (scene === void 0) { scene = null; }
  32820. var options = {
  32821. size: size,
  32822. sideOrientation: sideOrientation,
  32823. updatable: updatable
  32824. };
  32825. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32826. };
  32827. /**
  32828. * Creates a sphere mesh.
  32829. * Please consider using the same method from the MeshBuilder class instead.
  32830. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32831. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32835. */
  32836. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32837. var options = {
  32838. segments: segments,
  32839. diameterX: diameter,
  32840. diameterY: diameter,
  32841. diameterZ: diameter,
  32842. sideOrientation: sideOrientation,
  32843. updatable: updatable
  32844. };
  32845. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32846. };
  32847. /**
  32848. * Creates a cylinder or a cone mesh.
  32849. * Please consider using the same method from the MeshBuilder class instead.
  32850. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32851. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32852. * 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.
  32853. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32854. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32858. */
  32859. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32860. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32861. if (scene !== undefined) {
  32862. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32863. updatable = scene;
  32864. }
  32865. scene = subdivisions;
  32866. subdivisions = 1;
  32867. }
  32868. var options = {
  32869. height: height,
  32870. diameterTop: diameterTop,
  32871. diameterBottom: diameterBottom,
  32872. tessellation: tessellation,
  32873. subdivisions: subdivisions,
  32874. sideOrientation: sideOrientation,
  32875. updatable: updatable
  32876. };
  32877. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32878. };
  32879. // Torus (Code from SharpDX.org)
  32880. /**
  32881. * Creates a torus mesh.
  32882. * Please consider using the same method from the MeshBuilder class instead.
  32883. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32884. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32885. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32889. */
  32890. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32891. var options = {
  32892. diameter: diameter,
  32893. thickness: thickness,
  32894. tessellation: tessellation,
  32895. sideOrientation: sideOrientation,
  32896. updatable: updatable
  32897. };
  32898. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32899. };
  32900. /**
  32901. * Creates a torus knot mesh.
  32902. * Please consider using the same method from the MeshBuilder class instead.
  32903. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32904. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32905. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32906. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32910. */
  32911. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32912. var options = {
  32913. radius: radius,
  32914. tube: tube,
  32915. radialSegments: radialSegments,
  32916. tubularSegments: tubularSegments,
  32917. p: p,
  32918. q: q,
  32919. sideOrientation: sideOrientation,
  32920. updatable: updatable
  32921. };
  32922. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32923. };
  32924. /**
  32925. * Creates a line mesh.
  32926. * Please consider using the same method from the MeshBuilder class instead.
  32927. * 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.
  32928. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32929. * The parameter `points` is an array successive Vector3.
  32930. * 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
  32931. * When updating an instance, remember that only point positions can change, not the number of points.
  32932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32933. */
  32934. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32935. if (scene === void 0) { scene = null; }
  32936. if (updatable === void 0) { updatable = false; }
  32937. if (instance === void 0) { instance = null; }
  32938. var options = {
  32939. points: points,
  32940. updatable: updatable,
  32941. instance: instance
  32942. };
  32943. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32944. };
  32945. /**
  32946. * Creates a dashed line mesh.
  32947. * Please consider using the same method from the MeshBuilder class instead.
  32948. * 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.
  32949. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32950. * The parameter `points` is an array successive Vector3.
  32951. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32952. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32953. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32954. * 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
  32955. * When updating an instance, remember that only point positions can change, not the number of points.
  32956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32957. */
  32958. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32959. if (scene === void 0) { scene = null; }
  32960. var options = {
  32961. points: points,
  32962. dashSize: dashSize,
  32963. gapSize: gapSize,
  32964. dashNb: dashNb,
  32965. updatable: updatable,
  32966. instance: instance
  32967. };
  32968. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32969. };
  32970. /**
  32971. * Creates a polygon mesh.
  32972. * Please consider using the same method from the MeshBuilder class instead.
  32973. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32974. * 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.
  32975. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32977. * Remember you can only change the shape positions, not their number when updating a polygon.
  32978. */
  32979. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32980. var options = {
  32981. shape: shape,
  32982. holes: holes,
  32983. updatable: updatable,
  32984. sideOrientation: sideOrientation
  32985. };
  32986. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32987. };
  32988. /**
  32989. * Creates an extruded polygon mesh, with depth in the Y direction.
  32990. * Please consider using the same method from the MeshBuilder class instead.
  32991. */
  32992. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32993. var options = {
  32994. shape: shape,
  32995. holes: holes,
  32996. depth: depth,
  32997. updatable: updatable,
  32998. sideOrientation: sideOrientation
  32999. };
  33000. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33001. };
  33002. /**
  33003. * Creates an extruded shape mesh.
  33004. * 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.
  33005. * Please consider using the same method from the MeshBuilder class instead.
  33006. *
  33007. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33008. * 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
  33009. * extruded along the Z axis.
  33010. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33011. * 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.
  33012. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33013. * 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
  33014. * 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
  33015. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33019. */
  33020. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33021. if (scene === void 0) { scene = null; }
  33022. var options = {
  33023. shape: shape,
  33024. path: path,
  33025. scale: scale,
  33026. rotation: rotation,
  33027. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33028. sideOrientation: sideOrientation,
  33029. instance: instance,
  33030. updatable: updatable
  33031. };
  33032. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33033. };
  33034. /**
  33035. * Creates an custom extruded shape mesh.
  33036. * 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.
  33037. * Please consider using the same method from the MeshBuilder class instead.
  33038. *
  33039. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33040. * 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
  33041. * extruded along the Z axis.
  33042. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33043. * 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
  33044. * and the distance of this point from the begining of the path :
  33045. * ```javascript
  33046. * var rotationFunction = function(i, distance) {
  33047. * // do things
  33048. * return rotationValue; }
  33049. * ```
  33050. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33051. * 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
  33052. * and the distance of this point from the begining of the path :
  33053. * ```javascript
  33054. * var scaleFunction = function(i, distance) {
  33055. * // do things
  33056. * return scaleValue;}
  33057. * ```
  33058. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33059. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33060. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33061. * 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
  33062. * 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
  33063. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33067. */
  33068. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33069. var options = {
  33070. shape: shape,
  33071. path: path,
  33072. scaleFunction: scaleFunction,
  33073. rotationFunction: rotationFunction,
  33074. ribbonCloseArray: ribbonCloseArray,
  33075. ribbonClosePath: ribbonClosePath,
  33076. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33077. sideOrientation: sideOrientation,
  33078. instance: instance,
  33079. updatable: updatable
  33080. };
  33081. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33082. };
  33083. /**
  33084. * Creates lathe mesh.
  33085. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33086. * Please consider using the same method from the MeshBuilder class instead.
  33087. * 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
  33088. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33089. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33090. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33094. */
  33095. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33096. var options = {
  33097. shape: shape,
  33098. radius: radius,
  33099. tessellation: tessellation,
  33100. sideOrientation: sideOrientation,
  33101. updatable: updatable
  33102. };
  33103. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33104. };
  33105. /**
  33106. * Creates a plane mesh.
  33107. * Please consider using the same method from the MeshBuilder class instead.
  33108. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33112. */
  33113. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33114. var options = {
  33115. size: size,
  33116. width: size,
  33117. height: size,
  33118. sideOrientation: sideOrientation,
  33119. updatable: updatable
  33120. };
  33121. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33122. };
  33123. /**
  33124. * Creates a ground mesh.
  33125. * Please consider using the same method from the MeshBuilder class instead.
  33126. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33127. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33129. */
  33130. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33131. var options = {
  33132. width: width,
  33133. height: height,
  33134. subdivisions: subdivisions,
  33135. updatable: updatable
  33136. };
  33137. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33138. };
  33139. /**
  33140. * Creates a tiled ground mesh.
  33141. * Please consider using the same method from the MeshBuilder class instead.
  33142. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33143. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33144. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33145. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33146. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33147. * numbers of subdivisions on the ground width and height of each tile.
  33148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33149. */
  33150. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33151. var options = {
  33152. xmin: xmin,
  33153. zmin: zmin,
  33154. xmax: xmax,
  33155. zmax: zmax,
  33156. subdivisions: subdivisions,
  33157. precision: precision,
  33158. updatable: updatable
  33159. };
  33160. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33161. };
  33162. /**
  33163. * Creates a ground mesh from a height map.
  33164. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33165. * Please consider using the same method from the MeshBuilder class instead.
  33166. * The parameter `url` sets the URL of the height map image resource.
  33167. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33168. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33169. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33170. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33171. * 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).
  33172. * This function is passed the newly built mesh :
  33173. * ```javascript
  33174. * function(mesh) { // do things
  33175. * return; }
  33176. * ```
  33177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33178. */
  33179. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33180. var options = {
  33181. width: width,
  33182. height: height,
  33183. subdivisions: subdivisions,
  33184. minHeight: minHeight,
  33185. maxHeight: maxHeight,
  33186. updatable: updatable,
  33187. onReady: onReady
  33188. };
  33189. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33190. };
  33191. /**
  33192. * Creates a tube mesh.
  33193. * 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.
  33194. * Please consider using the same method from the MeshBuilder class instead.
  33195. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33196. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33197. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33198. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33199. * 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.
  33200. * It must return a radius value (positive float) :
  33201. * ```javascript
  33202. * var radiusFunction = function(i, distance) {
  33203. * // do things
  33204. * return radius; }
  33205. * ```
  33206. * 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
  33207. * 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
  33208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33209. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33211. */
  33212. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33213. var options = {
  33214. path: path,
  33215. radius: radius,
  33216. tessellation: tessellation,
  33217. radiusFunction: radiusFunction,
  33218. arc: 1,
  33219. cap: cap,
  33220. updatable: updatable,
  33221. sideOrientation: sideOrientation,
  33222. instance: instance
  33223. };
  33224. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33225. };
  33226. /**
  33227. * Creates a polyhedron mesh.
  33228. * Please consider using the same method from the MeshBuilder class instead.
  33229. * 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
  33230. * to choose the wanted type.
  33231. * The parameter `size` (positive float, default 1) sets the polygon size.
  33232. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33233. * 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`.
  33234. * 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
  33235. * 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)`).
  33236. * 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
  33237. * 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.
  33238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33241. */
  33242. Mesh.CreatePolyhedron = function (name, options, scene) {
  33243. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33244. };
  33245. /**
  33246. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33247. * Please consider using the same method from the MeshBuilder class instead.
  33248. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33249. * 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`).
  33250. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33251. * 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.
  33252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33255. */
  33256. Mesh.CreateIcoSphere = function (name, options, scene) {
  33257. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33258. };
  33259. /**
  33260. * Creates a decal mesh.
  33261. * Please consider using the same method from the MeshBuilder class instead.
  33262. * 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.
  33263. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33264. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33265. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33266. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33267. */
  33268. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33269. var options = {
  33270. position: position,
  33271. normal: normal,
  33272. size: size,
  33273. angle: angle
  33274. };
  33275. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33276. };
  33277. // Skeletons
  33278. /**
  33279. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33280. */
  33281. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33282. if (!this._sourcePositions) {
  33283. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33284. if (!source) {
  33285. return this._sourcePositions;
  33286. }
  33287. this._sourcePositions = new Float32Array(source);
  33288. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33289. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33290. }
  33291. }
  33292. return this._sourcePositions;
  33293. };
  33294. /**
  33295. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33296. */
  33297. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33298. if (!this._sourceNormals) {
  33299. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33300. if (!source) {
  33301. return this._sourceNormals;
  33302. }
  33303. this._sourceNormals = new Float32Array(source);
  33304. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33305. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33306. }
  33307. }
  33308. return this._sourceNormals;
  33309. };
  33310. /**
  33311. * Updates the vertex buffer by applying transformation from the bones.
  33312. * Returns the Mesh.
  33313. *
  33314. * @param {skeleton} skeleton to apply
  33315. */
  33316. Mesh.prototype.applySkeleton = function (skeleton) {
  33317. if (!this.geometry) {
  33318. return this;
  33319. }
  33320. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33321. return this;
  33322. }
  33323. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33324. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33325. return this;
  33326. }
  33327. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33328. return this;
  33329. }
  33330. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33331. return this;
  33332. }
  33333. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33334. return this;
  33335. }
  33336. if (!this._sourcePositions) {
  33337. var submeshes = this.subMeshes.slice();
  33338. this.setPositionsForCPUSkinning();
  33339. this.subMeshes = submeshes;
  33340. }
  33341. if (!this._sourceNormals) {
  33342. this.setNormalsForCPUSkinning();
  33343. }
  33344. // positionsData checks for not being Float32Array will only pass at most once
  33345. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33346. if (!positionsData) {
  33347. return this;
  33348. }
  33349. if (!(positionsData instanceof Float32Array)) {
  33350. positionsData = new Float32Array(positionsData);
  33351. }
  33352. // normalsData checks for not being Float32Array will only pass at most once
  33353. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33354. if (!normalsData) {
  33355. return this;
  33356. }
  33357. if (!(normalsData instanceof Float32Array)) {
  33358. normalsData = new Float32Array(normalsData);
  33359. }
  33360. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33361. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33362. if (!matricesWeightsData || !matricesIndicesData) {
  33363. return this;
  33364. }
  33365. var needExtras = this.numBoneInfluencers > 4;
  33366. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33367. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33368. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33369. var tempVector3 = BABYLON.Vector3.Zero();
  33370. var finalMatrix = new BABYLON.Matrix();
  33371. var tempMatrix = new BABYLON.Matrix();
  33372. var matWeightIdx = 0;
  33373. var inf;
  33374. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33375. var weight;
  33376. for (inf = 0; inf < 4; inf++) {
  33377. weight = matricesWeightsData[matWeightIdx + inf];
  33378. if (weight > 0) {
  33379. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33380. finalMatrix.addToSelf(tempMatrix);
  33381. }
  33382. else
  33383. break;
  33384. }
  33385. if (needExtras) {
  33386. for (inf = 0; inf < 4; inf++) {
  33387. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33388. if (weight > 0) {
  33389. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33390. finalMatrix.addToSelf(tempMatrix);
  33391. }
  33392. else
  33393. break;
  33394. }
  33395. }
  33396. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33397. tempVector3.toArray(positionsData, index);
  33398. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33399. tempVector3.toArray(normalsData, index);
  33400. finalMatrix.reset();
  33401. }
  33402. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33403. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33404. return this;
  33405. };
  33406. // Tools
  33407. /**
  33408. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33409. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33410. */
  33411. Mesh.MinMax = function (meshes) {
  33412. var minVector = null;
  33413. var maxVector = null;
  33414. meshes.forEach(function (mesh, index, array) {
  33415. var boundingInfo = mesh.getBoundingInfo();
  33416. var boundingBox = boundingInfo.boundingBox;
  33417. if (!minVector || !maxVector) {
  33418. minVector = boundingBox.minimumWorld;
  33419. maxVector = boundingBox.maximumWorld;
  33420. }
  33421. else {
  33422. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33423. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33424. }
  33425. });
  33426. if (!minVector || !maxVector) {
  33427. return {
  33428. min: BABYLON.Vector3.Zero(),
  33429. max: BABYLON.Vector3.Zero()
  33430. };
  33431. }
  33432. return {
  33433. min: minVector,
  33434. max: maxVector
  33435. };
  33436. };
  33437. /**
  33438. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33439. */
  33440. Mesh.Center = function (meshesOrMinMaxVector) {
  33441. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33442. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33443. };
  33444. /**
  33445. * Merge the array of meshes into a single mesh for performance reasons.
  33446. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33447. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33448. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33449. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33450. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33451. */
  33452. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33453. if (disposeSource === void 0) { disposeSource = true; }
  33454. var index;
  33455. if (!allow32BitsIndices) {
  33456. var totalVertices = 0;
  33457. // Counting vertices
  33458. for (index = 0; index < meshes.length; index++) {
  33459. if (meshes[index]) {
  33460. totalVertices += meshes[index].getTotalVertices();
  33461. if (totalVertices > 65536) {
  33462. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33463. return null;
  33464. }
  33465. }
  33466. }
  33467. }
  33468. // Merge
  33469. var vertexData = null;
  33470. var otherVertexData;
  33471. var indiceArray = new Array();
  33472. var source = null;
  33473. for (index = 0; index < meshes.length; index++) {
  33474. if (meshes[index]) {
  33475. meshes[index].computeWorldMatrix(true);
  33476. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33477. otherVertexData.transform(meshes[index].getWorldMatrix());
  33478. if (vertexData) {
  33479. vertexData.merge(otherVertexData);
  33480. }
  33481. else {
  33482. vertexData = otherVertexData;
  33483. source = meshes[index];
  33484. }
  33485. if (subdivideWithSubMeshes) {
  33486. indiceArray.push(meshes[index].getTotalIndices());
  33487. }
  33488. }
  33489. }
  33490. source = source;
  33491. if (!meshSubclass) {
  33492. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33493. }
  33494. vertexData.applyToMesh(meshSubclass);
  33495. // Setting properties
  33496. meshSubclass.material = source.material;
  33497. meshSubclass.checkCollisions = source.checkCollisions;
  33498. // Cleaning
  33499. if (disposeSource) {
  33500. for (index = 0; index < meshes.length; index++) {
  33501. if (meshes[index]) {
  33502. meshes[index].dispose();
  33503. }
  33504. }
  33505. }
  33506. // Subdivide
  33507. if (subdivideWithSubMeshes) {
  33508. //-- Suppresions du submesh global
  33509. meshSubclass.releaseSubMeshes();
  33510. index = 0;
  33511. var offset = 0;
  33512. //-- aplique la subdivision en fonction du tableau d'indices
  33513. while (index < indiceArray.length) {
  33514. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33515. offset += indiceArray[index];
  33516. index++;
  33517. }
  33518. }
  33519. return meshSubclass;
  33520. };
  33521. // Consts
  33522. Mesh._FRONTSIDE = 0;
  33523. Mesh._BACKSIDE = 1;
  33524. Mesh._DOUBLESIDE = 2;
  33525. Mesh._DEFAULTSIDE = 0;
  33526. Mesh._NO_CAP = 0;
  33527. Mesh._CAP_START = 1;
  33528. Mesh._CAP_END = 2;
  33529. Mesh._CAP_ALL = 3;
  33530. return Mesh;
  33531. }(BABYLON.AbstractMesh));
  33532. BABYLON.Mesh = Mesh;
  33533. })(BABYLON || (BABYLON = {}));
  33534. //# sourceMappingURL=babylon.mesh.js.map
  33535. var BABYLON;
  33536. (function (BABYLON) {
  33537. var BaseSubMesh = /** @class */ (function () {
  33538. function BaseSubMesh() {
  33539. }
  33540. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33541. get: function () {
  33542. return this._materialEffect;
  33543. },
  33544. enumerable: true,
  33545. configurable: true
  33546. });
  33547. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33548. if (defines === void 0) { defines = null; }
  33549. if (this._materialEffect === effect) {
  33550. if (!effect) {
  33551. this._materialDefines = null;
  33552. }
  33553. return;
  33554. }
  33555. this._materialDefines = defines;
  33556. this._materialEffect = effect;
  33557. };
  33558. return BaseSubMesh;
  33559. }());
  33560. BABYLON.BaseSubMesh = BaseSubMesh;
  33561. var SubMesh = /** @class */ (function (_super) {
  33562. __extends(SubMesh, _super);
  33563. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33564. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33565. var _this = _super.call(this) || this;
  33566. _this.materialIndex = materialIndex;
  33567. _this.verticesStart = verticesStart;
  33568. _this.verticesCount = verticesCount;
  33569. _this.indexStart = indexStart;
  33570. _this.indexCount = indexCount;
  33571. _this._renderId = 0;
  33572. _this._mesh = mesh;
  33573. _this._renderingMesh = renderingMesh || mesh;
  33574. mesh.subMeshes.push(_this);
  33575. _this._trianglePlanes = [];
  33576. _this._id = mesh.subMeshes.length - 1;
  33577. if (createBoundingBox) {
  33578. _this.refreshBoundingInfo();
  33579. mesh.computeWorldMatrix(true);
  33580. }
  33581. return _this;
  33582. }
  33583. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33584. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33585. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33586. };
  33587. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33588. get: function () {
  33589. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33590. },
  33591. enumerable: true,
  33592. configurable: true
  33593. });
  33594. /**
  33595. * Returns the submesh BoudingInfo object.
  33596. */
  33597. SubMesh.prototype.getBoundingInfo = function () {
  33598. if (this.IsGlobal) {
  33599. return this._mesh.getBoundingInfo();
  33600. }
  33601. return this._boundingInfo;
  33602. };
  33603. /**
  33604. * Sets the submesh BoundingInfo.
  33605. * Return the SubMesh.
  33606. */
  33607. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33608. this._boundingInfo = boundingInfo;
  33609. return this;
  33610. };
  33611. /**
  33612. * Returns the mesh of the current submesh.
  33613. */
  33614. SubMesh.prototype.getMesh = function () {
  33615. return this._mesh;
  33616. };
  33617. /**
  33618. * Returns the rendering mesh of the submesh.
  33619. */
  33620. SubMesh.prototype.getRenderingMesh = function () {
  33621. return this._renderingMesh;
  33622. };
  33623. /**
  33624. * Returns the submesh material.
  33625. */
  33626. SubMesh.prototype.getMaterial = function () {
  33627. var rootMaterial = this._renderingMesh.material;
  33628. if (rootMaterial === null || rootMaterial === undefined) {
  33629. return this._mesh.getScene().defaultMaterial;
  33630. }
  33631. else if (rootMaterial.getSubMaterial) {
  33632. var multiMaterial = rootMaterial;
  33633. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33634. if (this._currentMaterial !== effectiveMaterial) {
  33635. this._currentMaterial = effectiveMaterial;
  33636. this._materialDefines = null;
  33637. }
  33638. return effectiveMaterial;
  33639. }
  33640. return rootMaterial;
  33641. };
  33642. // Methods
  33643. /**
  33644. * Sets a new updated BoundingInfo object to the submesh.
  33645. * Returns the SubMesh.
  33646. */
  33647. SubMesh.prototype.refreshBoundingInfo = function () {
  33648. this._lastColliderWorldVertices = null;
  33649. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33650. return this;
  33651. }
  33652. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33653. if (!data) {
  33654. this._boundingInfo = this._mesh.getBoundingInfo();
  33655. return this;
  33656. }
  33657. var indices = this._renderingMesh.getIndices();
  33658. var extend;
  33659. //is this the only submesh?
  33660. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33661. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33662. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33663. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33664. }
  33665. else {
  33666. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33667. }
  33668. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33669. return this;
  33670. };
  33671. SubMesh.prototype._checkCollision = function (collider) {
  33672. var boundingInfo = this.getBoundingInfo();
  33673. return boundingInfo._checkCollision(collider);
  33674. };
  33675. /**
  33676. * Updates the submesh BoundingInfo.
  33677. * Returns the Submesh.
  33678. */
  33679. SubMesh.prototype.updateBoundingInfo = function (world) {
  33680. var boundingInfo = this.getBoundingInfo();
  33681. if (!boundingInfo) {
  33682. this.refreshBoundingInfo();
  33683. boundingInfo = this.getBoundingInfo();
  33684. }
  33685. boundingInfo.update(world);
  33686. return this;
  33687. };
  33688. /**
  33689. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33690. * Boolean returned.
  33691. */
  33692. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33693. var boundingInfo = this.getBoundingInfo();
  33694. if (!boundingInfo) {
  33695. return false;
  33696. }
  33697. return boundingInfo.isInFrustum(frustumPlanes);
  33698. };
  33699. /**
  33700. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33701. * Boolean returned.
  33702. */
  33703. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33704. var boundingInfo = this.getBoundingInfo();
  33705. if (!boundingInfo) {
  33706. return false;
  33707. }
  33708. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33709. };
  33710. /**
  33711. * Renders the submesh.
  33712. * Returns it.
  33713. */
  33714. SubMesh.prototype.render = function (enableAlphaMode) {
  33715. this._renderingMesh.render(this, enableAlphaMode);
  33716. return this;
  33717. };
  33718. /**
  33719. * Returns a new Index Buffer.
  33720. * Type returned : WebGLBuffer.
  33721. */
  33722. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33723. if (!this._linesIndexBuffer) {
  33724. var linesIndices = [];
  33725. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33726. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33727. }
  33728. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33729. this.linesIndexCount = linesIndices.length;
  33730. }
  33731. return this._linesIndexBuffer;
  33732. };
  33733. /**
  33734. * True is the passed Ray intersects the submesh bounding box.
  33735. * Boolean returned.
  33736. */
  33737. SubMesh.prototype.canIntersects = function (ray) {
  33738. var boundingInfo = this.getBoundingInfo();
  33739. if (!boundingInfo) {
  33740. return false;
  33741. }
  33742. return ray.intersectsBox(boundingInfo.boundingBox);
  33743. };
  33744. /**
  33745. * Returns an object IntersectionInfo.
  33746. */
  33747. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33748. var intersectInfo = null;
  33749. var material = this.getMaterial();
  33750. if (!material) {
  33751. return null;
  33752. }
  33753. switch (material.fillMode) {
  33754. case BABYLON.Material.PointListDrawMode:
  33755. case BABYLON.Material.LineListDrawMode:
  33756. case BABYLON.Material.LineLoopDrawMode:
  33757. case BABYLON.Material.LineStripDrawMode:
  33758. case BABYLON.Material.TriangleFanDrawMode:
  33759. case BABYLON.Material.TriangleStripDrawMode:
  33760. return null;
  33761. }
  33762. // LineMesh first as it's also a Mesh...
  33763. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33764. var lineMesh = this._mesh;
  33765. // Line test
  33766. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33767. var p0 = positions[indices[index]];
  33768. var p1 = positions[indices[index + 1]];
  33769. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33770. if (length < 0) {
  33771. continue;
  33772. }
  33773. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33774. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33775. if (fastCheck) {
  33776. break;
  33777. }
  33778. }
  33779. }
  33780. }
  33781. else {
  33782. // Triangles test
  33783. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33784. var p0 = positions[indices[index]];
  33785. var p1 = positions[indices[index + 1]];
  33786. var p2 = positions[indices[index + 2]];
  33787. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33788. if (currentIntersectInfo) {
  33789. if (currentIntersectInfo.distance < 0) {
  33790. continue;
  33791. }
  33792. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33793. intersectInfo = currentIntersectInfo;
  33794. intersectInfo.faceId = index / 3;
  33795. if (fastCheck) {
  33796. break;
  33797. }
  33798. }
  33799. }
  33800. }
  33801. }
  33802. return intersectInfo;
  33803. };
  33804. SubMesh.prototype._rebuild = function () {
  33805. if (this._linesIndexBuffer) {
  33806. this._linesIndexBuffer = null;
  33807. }
  33808. };
  33809. // Clone
  33810. /**
  33811. * Creates a new Submesh from the passed Mesh.
  33812. */
  33813. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33814. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33815. if (!this.IsGlobal) {
  33816. var boundingInfo = this.getBoundingInfo();
  33817. if (!boundingInfo) {
  33818. return result;
  33819. }
  33820. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33821. }
  33822. return result;
  33823. };
  33824. // Dispose
  33825. /**
  33826. * Disposes the Submesh.
  33827. * Returns nothing.
  33828. */
  33829. SubMesh.prototype.dispose = function () {
  33830. if (this._linesIndexBuffer) {
  33831. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33832. this._linesIndexBuffer = null;
  33833. }
  33834. // Remove from mesh
  33835. var index = this._mesh.subMeshes.indexOf(this);
  33836. this._mesh.subMeshes.splice(index, 1);
  33837. };
  33838. // Statics
  33839. /**
  33840. * Creates a new Submesh from the passed parameters :
  33841. * - materialIndex (integer) : the index of the main mesh material.
  33842. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33843. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33844. * - mesh (Mesh) : the main mesh to create the submesh from.
  33845. * - renderingMesh (optional Mesh) : rendering mesh.
  33846. */
  33847. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33848. var minVertexIndex = Number.MAX_VALUE;
  33849. var maxVertexIndex = -Number.MAX_VALUE;
  33850. renderingMesh = (renderingMesh || mesh);
  33851. var indices = renderingMesh.getIndices();
  33852. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33853. var vertexIndex = indices[index];
  33854. if (vertexIndex < minVertexIndex)
  33855. minVertexIndex = vertexIndex;
  33856. if (vertexIndex > maxVertexIndex)
  33857. maxVertexIndex = vertexIndex;
  33858. }
  33859. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33860. };
  33861. return SubMesh;
  33862. }(BaseSubMesh));
  33863. BABYLON.SubMesh = SubMesh;
  33864. })(BABYLON || (BABYLON = {}));
  33865. //# sourceMappingURL=babylon.subMesh.js.map
  33866. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33867. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33868. s = arguments[i];
  33869. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33870. t[p] = s[p];
  33871. }
  33872. return t;
  33873. };
  33874. var BABYLON;
  33875. (function (BABYLON) {
  33876. /**
  33877. * Manages the defines for the Material
  33878. */
  33879. var MaterialDefines = /** @class */ (function () {
  33880. function MaterialDefines() {
  33881. this._isDirty = true;
  33882. /** @ignore */
  33883. this._areLightsDirty = true;
  33884. /** @ignore */
  33885. this._areAttributesDirty = true;
  33886. /** @ignore */
  33887. this._areTexturesDirty = true;
  33888. /** @ignore */
  33889. this._areFresnelDirty = true;
  33890. /** @ignore */
  33891. this._areMiscDirty = true;
  33892. /** @ignore */
  33893. this._areImageProcessingDirty = true;
  33894. /** @ignore */
  33895. this._normals = false;
  33896. /** @ignore */
  33897. this._uvs = false;
  33898. /** @ignore */
  33899. this._needNormals = false;
  33900. /** @ignore */
  33901. this._needUVs = false;
  33902. }
  33903. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33904. /**
  33905. * Specifies if the material needs to be re-calculated
  33906. */
  33907. get: function () {
  33908. return this._isDirty;
  33909. },
  33910. enumerable: true,
  33911. configurable: true
  33912. });
  33913. /**
  33914. * Marks the material to indicate that it has been re-calculated
  33915. */
  33916. MaterialDefines.prototype.markAsProcessed = function () {
  33917. this._isDirty = false;
  33918. this._areAttributesDirty = false;
  33919. this._areTexturesDirty = false;
  33920. this._areFresnelDirty = false;
  33921. this._areLightsDirty = false;
  33922. this._areMiscDirty = false;
  33923. this._areImageProcessingDirty = false;
  33924. };
  33925. /**
  33926. * Marks the material to indicate that it needs to be re-calculated
  33927. */
  33928. MaterialDefines.prototype.markAsUnprocessed = function () {
  33929. this._isDirty = true;
  33930. };
  33931. /**
  33932. * Marks the material to indicate all of its defines need to be re-calculated
  33933. */
  33934. MaterialDefines.prototype.markAllAsDirty = function () {
  33935. this._areTexturesDirty = true;
  33936. this._areAttributesDirty = true;
  33937. this._areLightsDirty = true;
  33938. this._areFresnelDirty = true;
  33939. this._areMiscDirty = true;
  33940. this._areImageProcessingDirty = true;
  33941. this._isDirty = true;
  33942. };
  33943. /**
  33944. * Marks the material to indicate that image processing needs to be re-calculated
  33945. */
  33946. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33947. this._areImageProcessingDirty = true;
  33948. this._isDirty = true;
  33949. };
  33950. /**
  33951. * Marks the material to indicate the lights need to be re-calculated
  33952. */
  33953. MaterialDefines.prototype.markAsLightDirty = function () {
  33954. this._areLightsDirty = true;
  33955. this._isDirty = true;
  33956. };
  33957. /**
  33958. * Marks the attribute state as changed
  33959. */
  33960. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33961. this._areAttributesDirty = true;
  33962. this._isDirty = true;
  33963. };
  33964. /**
  33965. * Marks the texture state as changed
  33966. */
  33967. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33968. this._areTexturesDirty = true;
  33969. this._isDirty = true;
  33970. };
  33971. /**
  33972. * Marks the fresnel state as changed
  33973. */
  33974. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33975. this._areFresnelDirty = true;
  33976. this._isDirty = true;
  33977. };
  33978. /**
  33979. * Marks the misc state as changed
  33980. */
  33981. MaterialDefines.prototype.markAsMiscDirty = function () {
  33982. this._areMiscDirty = true;
  33983. this._isDirty = true;
  33984. };
  33985. /**
  33986. * Rebuilds the material defines
  33987. */
  33988. MaterialDefines.prototype.rebuild = function () {
  33989. if (this._keys) {
  33990. delete this._keys;
  33991. }
  33992. this._keys = [];
  33993. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33994. var key = _a[_i];
  33995. if (key[0] === "_") {
  33996. continue;
  33997. }
  33998. this._keys.push(key);
  33999. }
  34000. };
  34001. /**
  34002. * Specifies if two material defines are equal
  34003. * @param other - A material define instance to compare to
  34004. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34005. */
  34006. MaterialDefines.prototype.isEqual = function (other) {
  34007. if (this._keys.length !== other._keys.length) {
  34008. return false;
  34009. }
  34010. for (var index = 0; index < this._keys.length; index++) {
  34011. var prop = this._keys[index];
  34012. if (this[prop] !== other[prop]) {
  34013. return false;
  34014. }
  34015. }
  34016. return true;
  34017. };
  34018. /**
  34019. * Clones this instance's defines to another instance
  34020. * @param other - material defines to clone values to
  34021. */
  34022. MaterialDefines.prototype.cloneTo = function (other) {
  34023. if (this._keys.length !== other._keys.length) {
  34024. other._keys = this._keys.slice(0);
  34025. }
  34026. for (var index = 0; index < this._keys.length; index++) {
  34027. var prop = this._keys[index];
  34028. other[prop] = this[prop];
  34029. }
  34030. };
  34031. /**
  34032. * Resets the material define values
  34033. */
  34034. MaterialDefines.prototype.reset = function () {
  34035. for (var index = 0; index < this._keys.length; index++) {
  34036. var prop = this._keys[index];
  34037. var type = typeof this[prop];
  34038. switch (type) {
  34039. case "number":
  34040. this[prop] = 0;
  34041. break;
  34042. case "string":
  34043. this[prop] = "";
  34044. break;
  34045. default:
  34046. this[prop] = false;
  34047. break;
  34048. }
  34049. }
  34050. };
  34051. /**
  34052. * Converts the material define values to a string
  34053. * @returns - String of material define information
  34054. */
  34055. MaterialDefines.prototype.toString = function () {
  34056. var result = "";
  34057. for (var index = 0; index < this._keys.length; index++) {
  34058. var prop = this._keys[index];
  34059. var value = this[prop];
  34060. var type = typeof value;
  34061. switch (type) {
  34062. case "number":
  34063. case "string":
  34064. result += "#define " + prop + " " + value + "\n";
  34065. break;
  34066. default:
  34067. if (value) {
  34068. result += "#define " + prop + "\n";
  34069. }
  34070. break;
  34071. }
  34072. }
  34073. return result;
  34074. };
  34075. return MaterialDefines;
  34076. }());
  34077. BABYLON.MaterialDefines = MaterialDefines;
  34078. /**
  34079. * Base class for the main features of a material in Babylon.js
  34080. */
  34081. var Material = /** @class */ (function () {
  34082. /**
  34083. * Creates a material instance
  34084. * @param name defines the name of the material
  34085. * @param scene defines the scene to reference
  34086. * @param doNotAdd specifies if the material should be added to the scene
  34087. */
  34088. function Material(name, scene, doNotAdd) {
  34089. /**
  34090. * Specifies if the ready state should be checked on each call
  34091. */
  34092. this.checkReadyOnEveryCall = false;
  34093. /**
  34094. * Specifies if the ready state should be checked once
  34095. */
  34096. this.checkReadyOnlyOnce = false;
  34097. /**
  34098. * The state of the material
  34099. */
  34100. this.state = "";
  34101. /**
  34102. * The alpha value of the material
  34103. */
  34104. this._alpha = 1.0;
  34105. /**
  34106. * Specifies if back face culling is enabled
  34107. */
  34108. this._backFaceCulling = true;
  34109. /**
  34110. * Specifies if the material should be serialized
  34111. */
  34112. this.doNotSerialize = false;
  34113. /**
  34114. * Specifies if the effect should be stored on sub meshes
  34115. */
  34116. this.storeEffectOnSubMeshes = false;
  34117. /**
  34118. * An event triggered when the material is disposed
  34119. */
  34120. this.onDisposeObservable = new BABYLON.Observable();
  34121. /**
  34122. * An event triggered when the material is bound
  34123. */
  34124. this.onBindObservable = new BABYLON.Observable();
  34125. /**
  34126. * An event triggered when the material is unbound
  34127. */
  34128. this.onUnBindObservable = new BABYLON.Observable();
  34129. /**
  34130. * Stores the value of the alpha mode
  34131. */
  34132. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34133. /**
  34134. * Stores the state of the need depth pre-pass value
  34135. */
  34136. this._needDepthPrePass = false;
  34137. /**
  34138. * Specifies if depth writing should be disabled
  34139. */
  34140. this.disableDepthWrite = false;
  34141. /**
  34142. * Specifies if depth writing should be forced
  34143. */
  34144. this.forceDepthWrite = false;
  34145. /**
  34146. * Specifies if there should be a separate pass for culling
  34147. */
  34148. this.separateCullingPass = false;
  34149. /**
  34150. * Stores the state specifing if fog should be enabled
  34151. */
  34152. this._fogEnabled = true;
  34153. /**
  34154. * Stores the size of points
  34155. */
  34156. this.pointSize = 1.0;
  34157. /**
  34158. * Stores the z offset value
  34159. */
  34160. this.zOffset = 0;
  34161. /**
  34162. * Specifies if the material was previously ready
  34163. */
  34164. this._wasPreviouslyReady = false;
  34165. /**
  34166. * Stores the fill mode state
  34167. */
  34168. this._fillMode = Material.TriangleFillMode;
  34169. this.name = name;
  34170. this.id = name || BABYLON.Tools.RandomId();
  34171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34172. if (this._scene.useRightHandedSystem) {
  34173. this.sideOrientation = Material.ClockWiseSideOrientation;
  34174. }
  34175. else {
  34176. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34177. }
  34178. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34179. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34180. if (!doNotAdd) {
  34181. this._scene.materials.push(this);
  34182. }
  34183. }
  34184. Object.defineProperty(Material, "TriangleFillMode", {
  34185. /**
  34186. * Returns the triangle fill mode
  34187. */
  34188. get: function () {
  34189. return Material._TriangleFillMode;
  34190. },
  34191. enumerable: true,
  34192. configurable: true
  34193. });
  34194. Object.defineProperty(Material, "WireFrameFillMode", {
  34195. /**
  34196. * Returns the wireframe mode
  34197. */
  34198. get: function () {
  34199. return Material._WireFrameFillMode;
  34200. },
  34201. enumerable: true,
  34202. configurable: true
  34203. });
  34204. Object.defineProperty(Material, "PointFillMode", {
  34205. /**
  34206. * Returns the point fill mode
  34207. */
  34208. get: function () {
  34209. return Material._PointFillMode;
  34210. },
  34211. enumerable: true,
  34212. configurable: true
  34213. });
  34214. Object.defineProperty(Material, "PointListDrawMode", {
  34215. /**
  34216. * Returns the point list draw mode
  34217. */
  34218. get: function () {
  34219. return Material._PointListDrawMode;
  34220. },
  34221. enumerable: true,
  34222. configurable: true
  34223. });
  34224. Object.defineProperty(Material, "LineListDrawMode", {
  34225. /**
  34226. * Returns the line list draw mode
  34227. */
  34228. get: function () {
  34229. return Material._LineListDrawMode;
  34230. },
  34231. enumerable: true,
  34232. configurable: true
  34233. });
  34234. Object.defineProperty(Material, "LineLoopDrawMode", {
  34235. /**
  34236. * Returns the line loop draw mode
  34237. */
  34238. get: function () {
  34239. return Material._LineLoopDrawMode;
  34240. },
  34241. enumerable: true,
  34242. configurable: true
  34243. });
  34244. Object.defineProperty(Material, "LineStripDrawMode", {
  34245. /**
  34246. * Returns the line strip draw mode
  34247. */
  34248. get: function () {
  34249. return Material._LineStripDrawMode;
  34250. },
  34251. enumerable: true,
  34252. configurable: true
  34253. });
  34254. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34255. /**
  34256. * Returns the triangle strip draw mode
  34257. */
  34258. get: function () {
  34259. return Material._TriangleStripDrawMode;
  34260. },
  34261. enumerable: true,
  34262. configurable: true
  34263. });
  34264. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34265. /**
  34266. * Returns the triangle fan draw mode
  34267. */
  34268. get: function () {
  34269. return Material._TriangleFanDrawMode;
  34270. },
  34271. enumerable: true,
  34272. configurable: true
  34273. });
  34274. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34275. /**
  34276. * Returns the clock-wise side orientation
  34277. */
  34278. get: function () {
  34279. return Material._ClockWiseSideOrientation;
  34280. },
  34281. enumerable: true,
  34282. configurable: true
  34283. });
  34284. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34285. /**
  34286. * Returns the counter clock-wise side orientation
  34287. */
  34288. get: function () {
  34289. return Material._CounterClockWiseSideOrientation;
  34290. },
  34291. enumerable: true,
  34292. configurable: true
  34293. });
  34294. Object.defineProperty(Material, "TextureDirtyFlag", {
  34295. /**
  34296. * Returns the dirty texture flag value
  34297. */
  34298. get: function () {
  34299. return Material._TextureDirtyFlag;
  34300. },
  34301. enumerable: true,
  34302. configurable: true
  34303. });
  34304. Object.defineProperty(Material, "LightDirtyFlag", {
  34305. /**
  34306. * Returns the dirty light flag value
  34307. */
  34308. get: function () {
  34309. return Material._LightDirtyFlag;
  34310. },
  34311. enumerable: true,
  34312. configurable: true
  34313. });
  34314. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34315. /**
  34316. * Returns the dirty fresnel flag value
  34317. */
  34318. get: function () {
  34319. return Material._FresnelDirtyFlag;
  34320. },
  34321. enumerable: true,
  34322. configurable: true
  34323. });
  34324. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34325. /**
  34326. * Returns the dirty attributes flag value
  34327. */
  34328. get: function () {
  34329. return Material._AttributesDirtyFlag;
  34330. },
  34331. enumerable: true,
  34332. configurable: true
  34333. });
  34334. Object.defineProperty(Material, "MiscDirtyFlag", {
  34335. /**
  34336. * Returns the dirty misc flag value
  34337. */
  34338. get: function () {
  34339. return Material._MiscDirtyFlag;
  34340. },
  34341. enumerable: true,
  34342. configurable: true
  34343. });
  34344. Object.defineProperty(Material.prototype, "alpha", {
  34345. /**
  34346. * Gets the alpha value of the material
  34347. */
  34348. get: function () {
  34349. return this._alpha;
  34350. },
  34351. /**
  34352. * Sets the alpha value of the material
  34353. */
  34354. set: function (value) {
  34355. if (this._alpha === value) {
  34356. return;
  34357. }
  34358. this._alpha = value;
  34359. this.markAsDirty(Material.MiscDirtyFlag);
  34360. },
  34361. enumerable: true,
  34362. configurable: true
  34363. });
  34364. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34365. /**
  34366. * Gets the back-face culling state
  34367. */
  34368. get: function () {
  34369. return this._backFaceCulling;
  34370. },
  34371. /**
  34372. * Sets the back-face culling state
  34373. */
  34374. set: function (value) {
  34375. if (this._backFaceCulling === value) {
  34376. return;
  34377. }
  34378. this._backFaceCulling = value;
  34379. this.markAsDirty(Material.TextureDirtyFlag);
  34380. },
  34381. enumerable: true,
  34382. configurable: true
  34383. });
  34384. Object.defineProperty(Material.prototype, "onDispose", {
  34385. /**
  34386. * Called during a dispose event
  34387. */
  34388. set: function (callback) {
  34389. if (this._onDisposeObserver) {
  34390. this.onDisposeObservable.remove(this._onDisposeObserver);
  34391. }
  34392. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34393. },
  34394. enumerable: true,
  34395. configurable: true
  34396. });
  34397. Object.defineProperty(Material.prototype, "onBind", {
  34398. /**
  34399. * Called during a bind event
  34400. */
  34401. set: function (callback) {
  34402. if (this._onBindObserver) {
  34403. this.onBindObservable.remove(this._onBindObserver);
  34404. }
  34405. this._onBindObserver = this.onBindObservable.add(callback);
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(Material.prototype, "alphaMode", {
  34411. /**
  34412. * Gets the value of the alpha mode
  34413. */
  34414. get: function () {
  34415. return this._alphaMode;
  34416. },
  34417. /**
  34418. * Sets the value of the alpha mode.
  34419. *
  34420. * | Value | Type | Description |
  34421. * | --- | --- | --- |
  34422. * | 0 | ALPHA_DISABLE | |
  34423. * | 1 | ALPHA_ADD | |
  34424. * | 2 | ALPHA_COMBINE | |
  34425. * | 3 | ALPHA_SUBTRACT | |
  34426. * | 4 | ALPHA_MULTIPLY | |
  34427. * | 5 | ALPHA_MAXIMIZED | |
  34428. * | 6 | ALPHA_ONEONE | |
  34429. * | 7 | ALPHA_PREMULTIPLIED | |
  34430. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34431. * | 9 | ALPHA_INTERPOLATE | |
  34432. * | 10 | ALPHA_SCREENMODE | |
  34433. *
  34434. */
  34435. set: function (value) {
  34436. if (this._alphaMode === value) {
  34437. return;
  34438. }
  34439. this._alphaMode = value;
  34440. this.markAsDirty(Material.TextureDirtyFlag);
  34441. },
  34442. enumerable: true,
  34443. configurable: true
  34444. });
  34445. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34446. /**
  34447. * Gets the depth pre-pass value
  34448. */
  34449. get: function () {
  34450. return this._needDepthPrePass;
  34451. },
  34452. /**
  34453. * Sets the need depth pre-pass value
  34454. */
  34455. set: function (value) {
  34456. if (this._needDepthPrePass === value) {
  34457. return;
  34458. }
  34459. this._needDepthPrePass = value;
  34460. if (this._needDepthPrePass) {
  34461. this.checkReadyOnEveryCall = true;
  34462. }
  34463. },
  34464. enumerable: true,
  34465. configurable: true
  34466. });
  34467. Object.defineProperty(Material.prototype, "fogEnabled", {
  34468. /**
  34469. * Gets the value of the fog enabled state
  34470. */
  34471. get: function () {
  34472. return this._fogEnabled;
  34473. },
  34474. /**
  34475. * Sets the state for enabling fog
  34476. */
  34477. set: function (value) {
  34478. if (this._fogEnabled === value) {
  34479. return;
  34480. }
  34481. this._fogEnabled = value;
  34482. this.markAsDirty(Material.MiscDirtyFlag);
  34483. },
  34484. enumerable: true,
  34485. configurable: true
  34486. });
  34487. Object.defineProperty(Material.prototype, "wireframe", {
  34488. /**
  34489. * Gets a value specifying if wireframe mode is enabled
  34490. */
  34491. get: function () {
  34492. switch (this._fillMode) {
  34493. case Material.WireFrameFillMode:
  34494. case Material.LineListDrawMode:
  34495. case Material.LineLoopDrawMode:
  34496. case Material.LineStripDrawMode:
  34497. return true;
  34498. }
  34499. return this._scene.forceWireframe;
  34500. },
  34501. /**
  34502. * Sets the state of wireframe mode
  34503. */
  34504. set: function (value) {
  34505. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34506. },
  34507. enumerable: true,
  34508. configurable: true
  34509. });
  34510. Object.defineProperty(Material.prototype, "pointsCloud", {
  34511. /**
  34512. * Gets the value specifying if point clouds are enabled
  34513. */
  34514. get: function () {
  34515. switch (this._fillMode) {
  34516. case Material.PointFillMode:
  34517. case Material.PointListDrawMode:
  34518. return true;
  34519. }
  34520. return this._scene.forcePointsCloud;
  34521. },
  34522. /**
  34523. * Sets the state of point cloud mode
  34524. */
  34525. set: function (value) {
  34526. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(Material.prototype, "fillMode", {
  34532. /**
  34533. * Gets the material fill mode
  34534. */
  34535. get: function () {
  34536. return this._fillMode;
  34537. },
  34538. /**
  34539. * Sets the material fill mode
  34540. */
  34541. set: function (value) {
  34542. if (this._fillMode === value) {
  34543. return;
  34544. }
  34545. this._fillMode = value;
  34546. this.markAsDirty(Material.MiscDirtyFlag);
  34547. },
  34548. enumerable: true,
  34549. configurable: true
  34550. });
  34551. /**
  34552. * Returns a string representation of the current material
  34553. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34554. * @returns a string with material information
  34555. */
  34556. Material.prototype.toString = function (fullDetails) {
  34557. var ret = "Name: " + this.name;
  34558. if (fullDetails) {
  34559. }
  34560. return ret;
  34561. };
  34562. /**
  34563. * Gets the class name of the material
  34564. * @returns a string with the class name of the material
  34565. */
  34566. Material.prototype.getClassName = function () {
  34567. return "Material";
  34568. };
  34569. Object.defineProperty(Material.prototype, "isFrozen", {
  34570. /**
  34571. * Specifies if updates for the material been locked
  34572. */
  34573. get: function () {
  34574. return this.checkReadyOnlyOnce;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. /**
  34580. * Locks updates for the material
  34581. */
  34582. Material.prototype.freeze = function () {
  34583. this.checkReadyOnlyOnce = true;
  34584. };
  34585. /**
  34586. * Unlocks updates for the material
  34587. */
  34588. Material.prototype.unfreeze = function () {
  34589. this.checkReadyOnlyOnce = false;
  34590. };
  34591. /**
  34592. * Specifies if the material is ready to be used
  34593. * @param mesh defines the mesh to check
  34594. * @param useInstances specifies if instances should be used
  34595. * @returns a boolean indicating if the material is ready to be used
  34596. */
  34597. Material.prototype.isReady = function (mesh, useInstances) {
  34598. return true;
  34599. };
  34600. /**
  34601. * Specifies that the submesh is ready to be used
  34602. * @param mesh defines the mesh to check
  34603. * @param subMesh defines which submesh to check
  34604. * @param useInstances specifies that instances should be used
  34605. * @returns a boolean indicating that the submesh is ready or not
  34606. */
  34607. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34608. return false;
  34609. };
  34610. /**
  34611. * Returns the material effect
  34612. * @returns the effect associated with the material
  34613. */
  34614. Material.prototype.getEffect = function () {
  34615. return this._effect;
  34616. };
  34617. /**
  34618. * Returns the current scene
  34619. * @returns a Scene
  34620. */
  34621. Material.prototype.getScene = function () {
  34622. return this._scene;
  34623. };
  34624. /**
  34625. * Specifies if the material will require alpha blending
  34626. * @returns a boolean specifying if alpha blending is needed
  34627. */
  34628. Material.prototype.needAlphaBlending = function () {
  34629. return (this.alpha < 1.0);
  34630. };
  34631. /**
  34632. * Specifies if the mesh will require alpha blending
  34633. * @param mesh defines the mesh to check
  34634. * @returns a boolean specifying if alpha blending is needed for the mesh
  34635. */
  34636. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34637. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34638. };
  34639. /**
  34640. * Specifies if this material should be rendered in alpha test mode
  34641. * @returns a boolean specifying if an alpha test is needed.
  34642. */
  34643. Material.prototype.needAlphaTesting = function () {
  34644. return false;
  34645. };
  34646. /**
  34647. * Gets the texture used for the alpha test
  34648. * @returns the texture to use for alpha testing
  34649. */
  34650. Material.prototype.getAlphaTestTexture = function () {
  34651. return null;
  34652. };
  34653. /**
  34654. * Marks the material to indicate that it needs to be re-calculated
  34655. */
  34656. Material.prototype.markDirty = function () {
  34657. this._wasPreviouslyReady = false;
  34658. };
  34659. /** @ignore */
  34660. Material.prototype._preBind = function (effect, overrideOrientation) {
  34661. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34662. var engine = this._scene.getEngine();
  34663. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34664. var reverse = orientation === Material.ClockWiseSideOrientation;
  34665. engine.enableEffect(effect ? effect : this._effect);
  34666. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34667. return reverse;
  34668. };
  34669. /**
  34670. * Binds the material to the mesh
  34671. * @param world defines the world transformation matrix
  34672. * @param mesh defines the mesh to bind the material to
  34673. */
  34674. Material.prototype.bind = function (world, mesh) {
  34675. };
  34676. /**
  34677. * Binds the submesh to the material
  34678. * @param world defines the world transformation matrix
  34679. * @param mesh defines the mesh containing the submesh
  34680. * @param subMesh defines the submesh to bind the material to
  34681. */
  34682. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34683. };
  34684. /**
  34685. * Binds the world matrix to the material
  34686. * @param world defines the world transformation matrix
  34687. */
  34688. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34689. };
  34690. /**
  34691. * Binds the scene's uniform buffer to the effect.
  34692. * @param effect defines the effect to bind to the scene uniform buffer
  34693. * @param sceneUbo defines the uniform buffer storing scene data
  34694. */
  34695. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34696. sceneUbo.bindToEffect(effect, "Scene");
  34697. };
  34698. /**
  34699. * Binds the view matrix to the effect
  34700. * @param effect defines the effect to bind the view matrix to
  34701. */
  34702. Material.prototype.bindView = function (effect) {
  34703. if (!this._useUBO) {
  34704. effect.setMatrix("view", this.getScene().getViewMatrix());
  34705. }
  34706. else {
  34707. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34708. }
  34709. };
  34710. /**
  34711. * Binds the view projection matrix to the effect
  34712. * @param effect defines the effect to bind the view projection matrix to
  34713. */
  34714. Material.prototype.bindViewProjection = function (effect) {
  34715. if (!this._useUBO) {
  34716. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34717. }
  34718. else {
  34719. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34720. }
  34721. };
  34722. /**
  34723. * Specifies if material alpha testing should be turned on for the mesh
  34724. * @param mesh defines the mesh to check
  34725. */
  34726. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34727. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34728. };
  34729. /**
  34730. * Processes to execute after binding the material to a mesh
  34731. * @param mesh defines the rendered mesh
  34732. */
  34733. Material.prototype._afterBind = function (mesh) {
  34734. this._scene._cachedMaterial = this;
  34735. if (mesh) {
  34736. this._scene._cachedVisibility = mesh.visibility;
  34737. }
  34738. else {
  34739. this._scene._cachedVisibility = 1;
  34740. }
  34741. if (mesh) {
  34742. this.onBindObservable.notifyObservers(mesh);
  34743. }
  34744. if (this.disableDepthWrite) {
  34745. var engine = this._scene.getEngine();
  34746. this._cachedDepthWriteState = engine.getDepthWrite();
  34747. engine.setDepthWrite(false);
  34748. }
  34749. };
  34750. /**
  34751. * Unbinds the material from the mesh
  34752. */
  34753. Material.prototype.unbind = function () {
  34754. this.onUnBindObservable.notifyObservers(this);
  34755. if (this.disableDepthWrite) {
  34756. var engine = this._scene.getEngine();
  34757. engine.setDepthWrite(this._cachedDepthWriteState);
  34758. }
  34759. };
  34760. /**
  34761. * Gets the active textures from the material
  34762. * @returns an array of textures
  34763. */
  34764. Material.prototype.getActiveTextures = function () {
  34765. return [];
  34766. };
  34767. /**
  34768. * Specifies if the material uses a texture
  34769. * @param texture defines the texture to check against the material
  34770. * @returns a boolean specifying if the material uses the texture
  34771. */
  34772. Material.prototype.hasTexture = function (texture) {
  34773. return false;
  34774. };
  34775. /**
  34776. * Makes a duplicate of the material, and gives it a new name
  34777. * @param name defines the new name for the duplicated material
  34778. * @returns the cloned material
  34779. */
  34780. Material.prototype.clone = function (name) {
  34781. return null;
  34782. };
  34783. /**
  34784. * Gets the meshes bound to the material
  34785. * @returns an array of meshes bound to the material
  34786. */
  34787. Material.prototype.getBindedMeshes = function () {
  34788. var result = new Array();
  34789. for (var index = 0; index < this._scene.meshes.length; index++) {
  34790. var mesh = this._scene.meshes[index];
  34791. if (mesh.material === this) {
  34792. result.push(mesh);
  34793. }
  34794. }
  34795. return result;
  34796. };
  34797. /**
  34798. * Force shader compilation
  34799. * @param mesh defines the mesh associated with this material
  34800. * @param onCompiled defines a function to execute once the material is compiled
  34801. * @param options defines the options to configure the compilation
  34802. */
  34803. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34804. var _this = this;
  34805. var localOptions = __assign({ clipPlane: false }, options);
  34806. var subMesh = new BABYLON.BaseSubMesh();
  34807. var scene = this.getScene();
  34808. var checkReady = function () {
  34809. if (!_this._scene || !_this._scene.getEngine()) {
  34810. return;
  34811. }
  34812. if (subMesh._materialDefines) {
  34813. subMesh._materialDefines._renderId = -1;
  34814. }
  34815. var clipPlaneState = scene.clipPlane;
  34816. if (localOptions.clipPlane) {
  34817. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34818. }
  34819. if (_this.storeEffectOnSubMeshes) {
  34820. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34821. if (onCompiled) {
  34822. onCompiled(_this);
  34823. }
  34824. }
  34825. else {
  34826. setTimeout(checkReady, 16);
  34827. }
  34828. }
  34829. else {
  34830. if (_this.isReady(mesh)) {
  34831. if (onCompiled) {
  34832. onCompiled(_this);
  34833. }
  34834. }
  34835. else {
  34836. setTimeout(checkReady, 16);
  34837. }
  34838. }
  34839. if (localOptions.clipPlane) {
  34840. scene.clipPlane = clipPlaneState;
  34841. }
  34842. };
  34843. checkReady();
  34844. };
  34845. /**
  34846. * Force shader compilation
  34847. * @param mesh defines the mesh that will use this material
  34848. * @param options defines additional options for compiling the shaders
  34849. * @returns a promise that resolves when the compilation completes
  34850. */
  34851. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34852. var _this = this;
  34853. return new Promise(function (resolve) {
  34854. _this.forceCompilation(mesh, function () {
  34855. resolve();
  34856. }, options);
  34857. });
  34858. };
  34859. /**
  34860. * Marks a define in the material to indicate that it needs to be re-computed
  34861. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34862. */
  34863. Material.prototype.markAsDirty = function (flag) {
  34864. if (flag & Material.TextureDirtyFlag) {
  34865. this._markAllSubMeshesAsTexturesDirty();
  34866. }
  34867. if (flag & Material.LightDirtyFlag) {
  34868. this._markAllSubMeshesAsLightsDirty();
  34869. }
  34870. if (flag & Material.FresnelDirtyFlag) {
  34871. this._markAllSubMeshesAsFresnelDirty();
  34872. }
  34873. if (flag & Material.AttributesDirtyFlag) {
  34874. this._markAllSubMeshesAsAttributesDirty();
  34875. }
  34876. if (flag & Material.MiscDirtyFlag) {
  34877. this._markAllSubMeshesAsMiscDirty();
  34878. }
  34879. this.getScene().resetCachedMaterial();
  34880. };
  34881. /**
  34882. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34883. * @param func defines a function which checks material defines against the submeshes
  34884. */
  34885. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34886. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34887. var mesh = _a[_i];
  34888. if (!mesh.subMeshes) {
  34889. continue;
  34890. }
  34891. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34892. var subMesh = _c[_b];
  34893. if (subMesh.getMaterial() !== this) {
  34894. continue;
  34895. }
  34896. if (!subMesh._materialDefines) {
  34897. continue;
  34898. }
  34899. func(subMesh._materialDefines);
  34900. }
  34901. }
  34902. };
  34903. /**
  34904. * Indicates that image processing needs to be re-calculated for all submeshes
  34905. */
  34906. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34907. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34908. };
  34909. /**
  34910. * Indicates that textures need to be re-calculated for all submeshes
  34911. */
  34912. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34913. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34914. };
  34915. /**
  34916. * Indicates that fresnel needs to be re-calculated for all submeshes
  34917. */
  34918. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34919. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34920. };
  34921. /**
  34922. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34923. */
  34924. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34925. this._markAllSubMeshesAsDirty(function (defines) {
  34926. defines.markAsFresnelDirty();
  34927. defines.markAsMiscDirty();
  34928. });
  34929. };
  34930. /**
  34931. * Indicates that lights need to be re-calculated for all submeshes
  34932. */
  34933. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34934. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34935. };
  34936. /**
  34937. * Indicates that attributes need to be re-calculated for all submeshes
  34938. */
  34939. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34940. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34941. };
  34942. /**
  34943. * Indicates that misc needs to be re-calculated for all submeshes
  34944. */
  34945. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34946. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34947. };
  34948. /**
  34949. * Indicates that textures and misc need to be re-calculated for all submeshes
  34950. */
  34951. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34952. this._markAllSubMeshesAsDirty(function (defines) {
  34953. defines.markAsTexturesDirty();
  34954. defines.markAsMiscDirty();
  34955. });
  34956. };
  34957. /**
  34958. * Disposes the material
  34959. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34960. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34961. */
  34962. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34963. // Animations
  34964. this.getScene().stopAnimation(this);
  34965. this.getScene().freeProcessedMaterials();
  34966. // Remove from scene
  34967. var index = this._scene.materials.indexOf(this);
  34968. if (index >= 0) {
  34969. this._scene.materials.splice(index, 1);
  34970. }
  34971. // Remove from meshes
  34972. for (index = 0; index < this._scene.meshes.length; index++) {
  34973. var mesh = this._scene.meshes[index];
  34974. if (mesh.material === this) {
  34975. mesh.material = null;
  34976. if (mesh.geometry) {
  34977. var geometry = (mesh.geometry);
  34978. if (this.storeEffectOnSubMeshes) {
  34979. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34980. var subMesh = _a[_i];
  34981. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34982. if (forceDisposeEffect && subMesh._materialEffect) {
  34983. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34984. }
  34985. }
  34986. }
  34987. else {
  34988. geometry._releaseVertexArrayObject(this._effect);
  34989. }
  34990. }
  34991. }
  34992. }
  34993. this._uniformBuffer.dispose();
  34994. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34995. if (forceDisposeEffect && this._effect) {
  34996. if (!this.storeEffectOnSubMeshes) {
  34997. this._scene.getEngine()._releaseEffect(this._effect);
  34998. }
  34999. this._effect = null;
  35000. }
  35001. // Callback
  35002. this.onDisposeObservable.notifyObservers(this);
  35003. this.onDisposeObservable.clear();
  35004. this.onBindObservable.clear();
  35005. this.onUnBindObservable.clear();
  35006. };
  35007. /**
  35008. * Serializes this material
  35009. * @returns the serialized material object
  35010. */
  35011. Material.prototype.serialize = function () {
  35012. return BABYLON.SerializationHelper.Serialize(this);
  35013. };
  35014. /**
  35015. * Creates a MultiMaterial from parsed MultiMaterial data.
  35016. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35017. * @param scene defines the hosting scene
  35018. * @returns a new MultiMaterial
  35019. */
  35020. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35021. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35022. multiMaterial.id = parsedMultiMaterial.id;
  35023. if (BABYLON.Tags) {
  35024. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35025. }
  35026. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35027. var subMatId = parsedMultiMaterial.materials[matIndex];
  35028. if (subMatId) {
  35029. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35030. }
  35031. else {
  35032. multiMaterial.subMaterials.push(null);
  35033. }
  35034. }
  35035. return multiMaterial;
  35036. };
  35037. /**
  35038. * Creates a material from parsed material data
  35039. * @param parsedMaterial defines parsed material data
  35040. * @param scene defines the hosting scene
  35041. * @param rootUrl defines the root URL to use to load textures
  35042. * @returns a new material
  35043. */
  35044. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35045. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35046. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35047. }
  35048. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35049. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35050. if (!BABYLON.LegacyPBRMaterial) {
  35051. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35052. return;
  35053. }
  35054. }
  35055. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35056. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35057. ;
  35058. };
  35059. // Triangle views
  35060. Material._TriangleFillMode = 0;
  35061. Material._WireFrameFillMode = 1;
  35062. Material._PointFillMode = 2;
  35063. // Draw modes
  35064. Material._PointListDrawMode = 3;
  35065. Material._LineListDrawMode = 4;
  35066. Material._LineLoopDrawMode = 5;
  35067. Material._LineStripDrawMode = 6;
  35068. Material._TriangleStripDrawMode = 7;
  35069. Material._TriangleFanDrawMode = 8;
  35070. /**
  35071. * Stores the clock-wise side orientation
  35072. */
  35073. Material._ClockWiseSideOrientation = 0;
  35074. /**
  35075. * Stores the counter clock-wise side orientation
  35076. */
  35077. Material._CounterClockWiseSideOrientation = 1;
  35078. /**
  35079. * The dirty texture flag value
  35080. */
  35081. Material._TextureDirtyFlag = 1;
  35082. /**
  35083. * The dirty light flag value
  35084. */
  35085. Material._LightDirtyFlag = 2;
  35086. /**
  35087. * The dirty fresnel flag value
  35088. */
  35089. Material._FresnelDirtyFlag = 4;
  35090. /**
  35091. * The dirty attribute flag value
  35092. */
  35093. Material._AttributesDirtyFlag = 8;
  35094. /**
  35095. * The dirty misc flag value
  35096. */
  35097. Material._MiscDirtyFlag = 16;
  35098. __decorate([
  35099. BABYLON.serialize()
  35100. ], Material.prototype, "id", void 0);
  35101. __decorate([
  35102. BABYLON.serialize()
  35103. ], Material.prototype, "name", void 0);
  35104. __decorate([
  35105. BABYLON.serialize()
  35106. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35107. __decorate([
  35108. BABYLON.serialize()
  35109. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35110. __decorate([
  35111. BABYLON.serialize()
  35112. ], Material.prototype, "state", void 0);
  35113. __decorate([
  35114. BABYLON.serialize("alpha")
  35115. ], Material.prototype, "_alpha", void 0);
  35116. __decorate([
  35117. BABYLON.serialize("backFaceCulling")
  35118. ], Material.prototype, "_backFaceCulling", void 0);
  35119. __decorate([
  35120. BABYLON.serialize()
  35121. ], Material.prototype, "sideOrientation", void 0);
  35122. __decorate([
  35123. BABYLON.serialize("alphaMode")
  35124. ], Material.prototype, "_alphaMode", void 0);
  35125. __decorate([
  35126. BABYLON.serialize()
  35127. ], Material.prototype, "_needDepthPrePass", void 0);
  35128. __decorate([
  35129. BABYLON.serialize()
  35130. ], Material.prototype, "disableDepthWrite", void 0);
  35131. __decorate([
  35132. BABYLON.serialize()
  35133. ], Material.prototype, "forceDepthWrite", void 0);
  35134. __decorate([
  35135. BABYLON.serialize()
  35136. ], Material.prototype, "separateCullingPass", void 0);
  35137. __decorate([
  35138. BABYLON.serialize("fogEnabled")
  35139. ], Material.prototype, "_fogEnabled", void 0);
  35140. __decorate([
  35141. BABYLON.serialize()
  35142. ], Material.prototype, "pointSize", void 0);
  35143. __decorate([
  35144. BABYLON.serialize()
  35145. ], Material.prototype, "zOffset", void 0);
  35146. __decorate([
  35147. BABYLON.serialize()
  35148. ], Material.prototype, "wireframe", null);
  35149. __decorate([
  35150. BABYLON.serialize()
  35151. ], Material.prototype, "pointsCloud", null);
  35152. __decorate([
  35153. BABYLON.serialize()
  35154. ], Material.prototype, "fillMode", null);
  35155. return Material;
  35156. }());
  35157. BABYLON.Material = Material;
  35158. })(BABYLON || (BABYLON = {}));
  35159. //# sourceMappingURL=babylon.material.js.map
  35160. var BABYLON;
  35161. (function (BABYLON) {
  35162. var UniformBuffer = /** @class */ (function () {
  35163. /**
  35164. * Uniform buffer objects.
  35165. *
  35166. * Handles blocks of uniform on the GPU.
  35167. *
  35168. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35169. *
  35170. * For more information, please refer to :
  35171. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35172. */
  35173. function UniformBuffer(engine, data, dynamic) {
  35174. this._engine = engine;
  35175. this._noUBO = !engine.supportsUniformBuffers;
  35176. this._dynamic = dynamic;
  35177. this._data = data || [];
  35178. this._uniformLocations = {};
  35179. this._uniformSizes = {};
  35180. this._uniformLocationPointer = 0;
  35181. this._needSync = false;
  35182. if (this._noUBO) {
  35183. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35184. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35185. this.updateFloat = this._updateFloatForEffect;
  35186. this.updateFloat2 = this._updateFloat2ForEffect;
  35187. this.updateFloat3 = this._updateFloat3ForEffect;
  35188. this.updateFloat4 = this._updateFloat4ForEffect;
  35189. this.updateMatrix = this._updateMatrixForEffect;
  35190. this.updateVector3 = this._updateVector3ForEffect;
  35191. this.updateVector4 = this._updateVector4ForEffect;
  35192. this.updateColor3 = this._updateColor3ForEffect;
  35193. this.updateColor4 = this._updateColor4ForEffect;
  35194. }
  35195. else {
  35196. this._engine._uniformBuffers.push(this);
  35197. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35198. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35199. this.updateFloat = this._updateFloatForUniform;
  35200. this.updateFloat2 = this._updateFloat2ForUniform;
  35201. this.updateFloat3 = this._updateFloat3ForUniform;
  35202. this.updateFloat4 = this._updateFloat4ForUniform;
  35203. this.updateMatrix = this._updateMatrixForUniform;
  35204. this.updateVector3 = this._updateVector3ForUniform;
  35205. this.updateVector4 = this._updateVector4ForUniform;
  35206. this.updateColor3 = this._updateColor3ForUniform;
  35207. this.updateColor4 = this._updateColor4ForUniform;
  35208. }
  35209. }
  35210. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35211. // Properties
  35212. /**
  35213. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35214. * or just falling back on setUniformXXX calls.
  35215. */
  35216. get: function () {
  35217. return !this._noUBO;
  35218. },
  35219. enumerable: true,
  35220. configurable: true
  35221. });
  35222. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35223. /**
  35224. * Indicates if the WebGL underlying uniform buffer is in sync
  35225. * with the javascript cache data.
  35226. */
  35227. get: function () {
  35228. return !this._needSync;
  35229. },
  35230. enumerable: true,
  35231. configurable: true
  35232. });
  35233. /**
  35234. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35235. * Also, a dynamic UniformBuffer will disable cache verification and always
  35236. * update the underlying WebGL uniform buffer to the GPU.
  35237. */
  35238. UniformBuffer.prototype.isDynamic = function () {
  35239. return this._dynamic !== undefined;
  35240. };
  35241. /**
  35242. * The data cache on JS side.
  35243. */
  35244. UniformBuffer.prototype.getData = function () {
  35245. return this._bufferData;
  35246. };
  35247. /**
  35248. * The underlying WebGL Uniform buffer.
  35249. */
  35250. UniformBuffer.prototype.getBuffer = function () {
  35251. return this._buffer;
  35252. };
  35253. /**
  35254. * std140 layout specifies how to align data within an UBO structure.
  35255. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35256. * for specs.
  35257. */
  35258. UniformBuffer.prototype._fillAlignment = function (size) {
  35259. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35260. // and 4x4 matrices
  35261. // TODO : change if other types are used
  35262. var alignment;
  35263. if (size <= 2) {
  35264. alignment = size;
  35265. }
  35266. else {
  35267. alignment = 4;
  35268. }
  35269. if ((this._uniformLocationPointer % alignment) !== 0) {
  35270. var oldPointer = this._uniformLocationPointer;
  35271. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35272. var diff = this._uniformLocationPointer - oldPointer;
  35273. for (var i = 0; i < diff; i++) {
  35274. this._data.push(0);
  35275. }
  35276. }
  35277. };
  35278. /**
  35279. * Adds an uniform in the buffer.
  35280. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35281. * for the layout to be correct !
  35282. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35283. * @param {number|number[]} size Data size, or data directly.
  35284. */
  35285. UniformBuffer.prototype.addUniform = function (name, size) {
  35286. if (this._noUBO) {
  35287. return;
  35288. }
  35289. if (this._uniformLocations[name] !== undefined) {
  35290. // Already existing uniform
  35291. return;
  35292. }
  35293. // This function must be called in the order of the shader layout !
  35294. // size can be the size of the uniform, or data directly
  35295. var data;
  35296. if (size instanceof Array) {
  35297. data = size;
  35298. size = data.length;
  35299. }
  35300. else {
  35301. size = size;
  35302. data = [];
  35303. // Fill with zeros
  35304. for (var i = 0; i < size; i++) {
  35305. data.push(0);
  35306. }
  35307. }
  35308. this._fillAlignment(size);
  35309. this._uniformSizes[name] = size;
  35310. this._uniformLocations[name] = this._uniformLocationPointer;
  35311. this._uniformLocationPointer += size;
  35312. for (var i = 0; i < size; i++) {
  35313. this._data.push(data[i]);
  35314. }
  35315. this._needSync = true;
  35316. };
  35317. /**
  35318. * Wrapper for addUniform.
  35319. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35320. * @param {Matrix} mat A 4x4 matrix.
  35321. */
  35322. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35323. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35324. };
  35325. /**
  35326. * Wrapper for addUniform.
  35327. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35328. * @param {number} x
  35329. * @param {number} y
  35330. */
  35331. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35332. var temp = [x, y];
  35333. this.addUniform(name, temp);
  35334. };
  35335. /**
  35336. * Wrapper for addUniform.
  35337. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35338. * @param {number} x
  35339. * @param {number} y
  35340. * @param {number} z
  35341. */
  35342. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35343. var temp = [x, y, z];
  35344. this.addUniform(name, temp);
  35345. };
  35346. /**
  35347. * Wrapper for addUniform.
  35348. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35349. * @param {Color3} color
  35350. */
  35351. UniformBuffer.prototype.addColor3 = function (name, color) {
  35352. var temp = new Array();
  35353. color.toArray(temp);
  35354. this.addUniform(name, temp);
  35355. };
  35356. /**
  35357. * Wrapper for addUniform.
  35358. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35359. * @param {Color3} color
  35360. * @param {number} alpha
  35361. */
  35362. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35363. var temp = new Array();
  35364. color.toArray(temp);
  35365. temp.push(alpha);
  35366. this.addUniform(name, temp);
  35367. };
  35368. /**
  35369. * Wrapper for addUniform.
  35370. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35371. * @param {Vector3} vector
  35372. */
  35373. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35374. var temp = new Array();
  35375. vector.toArray(temp);
  35376. this.addUniform(name, temp);
  35377. };
  35378. /**
  35379. * Wrapper for addUniform.
  35380. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35381. */
  35382. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35383. this.addUniform(name, 12);
  35384. };
  35385. /**
  35386. * Wrapper for addUniform.
  35387. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35388. */
  35389. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35390. this.addUniform(name, 8);
  35391. };
  35392. /**
  35393. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35394. */
  35395. UniformBuffer.prototype.create = function () {
  35396. if (this._noUBO) {
  35397. return;
  35398. }
  35399. if (this._buffer) {
  35400. return; // nothing to do
  35401. }
  35402. // See spec, alignment must be filled as a vec4
  35403. this._fillAlignment(4);
  35404. this._bufferData = new Float32Array(this._data);
  35405. this._rebuild();
  35406. this._needSync = true;
  35407. };
  35408. UniformBuffer.prototype._rebuild = function () {
  35409. if (this._noUBO) {
  35410. return;
  35411. }
  35412. if (this._dynamic) {
  35413. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35414. }
  35415. else {
  35416. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35417. }
  35418. };
  35419. /**
  35420. * Updates the WebGL Uniform Buffer on the GPU.
  35421. * If the `dynamic` flag is set to true, no cache comparison is done.
  35422. * Otherwise, the buffer will be updated only if the cache differs.
  35423. */
  35424. UniformBuffer.prototype.update = function () {
  35425. if (!this._buffer) {
  35426. this.create();
  35427. return;
  35428. }
  35429. if (!this._dynamic && !this._needSync) {
  35430. return;
  35431. }
  35432. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35433. this._needSync = false;
  35434. };
  35435. /**
  35436. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35437. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35438. * @param {number[]|Float32Array} data Flattened data
  35439. * @param {number} size Size of the data.
  35440. */
  35441. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35442. var location = this._uniformLocations[uniformName];
  35443. if (location === undefined) {
  35444. if (this._buffer) {
  35445. // Cannot add an uniform if the buffer is already created
  35446. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35447. return;
  35448. }
  35449. this.addUniform(uniformName, size);
  35450. location = this._uniformLocations[uniformName];
  35451. }
  35452. if (!this._buffer) {
  35453. this.create();
  35454. }
  35455. if (!this._dynamic) {
  35456. // Cache for static uniform buffers
  35457. var changed = false;
  35458. for (var i = 0; i < size; i++) {
  35459. if (this._bufferData[location + i] !== data[i]) {
  35460. changed = true;
  35461. this._bufferData[location + i] = data[i];
  35462. }
  35463. }
  35464. this._needSync = this._needSync || changed;
  35465. }
  35466. else {
  35467. // No cache for dynamic
  35468. for (var i = 0; i < size; i++) {
  35469. this._bufferData[location + i] = data[i];
  35470. }
  35471. }
  35472. };
  35473. // Update methods
  35474. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35475. // To match std140, matrix must be realigned
  35476. for (var i = 0; i < 3; i++) {
  35477. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35478. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35479. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35480. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35481. }
  35482. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35483. };
  35484. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35485. this._currentEffect.setMatrix3x3(name, matrix);
  35486. };
  35487. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35488. this._currentEffect.setMatrix2x2(name, matrix);
  35489. };
  35490. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35491. // To match std140, matrix must be realigned
  35492. for (var i = 0; i < 2; i++) {
  35493. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35494. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35495. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35496. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35497. }
  35498. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35499. };
  35500. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35501. this._currentEffect.setFloat(name, x);
  35502. };
  35503. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35504. UniformBuffer._tempBuffer[0] = x;
  35505. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35506. };
  35507. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35508. if (suffix === void 0) { suffix = ""; }
  35509. this._currentEffect.setFloat2(name + suffix, x, y);
  35510. };
  35511. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35512. if (suffix === void 0) { suffix = ""; }
  35513. UniformBuffer._tempBuffer[0] = x;
  35514. UniformBuffer._tempBuffer[1] = y;
  35515. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35516. };
  35517. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35518. if (suffix === void 0) { suffix = ""; }
  35519. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35520. };
  35521. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35522. if (suffix === void 0) { suffix = ""; }
  35523. UniformBuffer._tempBuffer[0] = x;
  35524. UniformBuffer._tempBuffer[1] = y;
  35525. UniformBuffer._tempBuffer[2] = z;
  35526. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35527. };
  35528. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35529. if (suffix === void 0) { suffix = ""; }
  35530. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35531. };
  35532. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35533. if (suffix === void 0) { suffix = ""; }
  35534. UniformBuffer._tempBuffer[0] = x;
  35535. UniformBuffer._tempBuffer[1] = y;
  35536. UniformBuffer._tempBuffer[2] = z;
  35537. UniformBuffer._tempBuffer[3] = w;
  35538. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35539. };
  35540. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35541. this._currentEffect.setMatrix(name, mat);
  35542. };
  35543. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35544. this.updateUniform(name, mat.toArray(), 16);
  35545. };
  35546. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35547. this._currentEffect.setVector3(name, vector);
  35548. };
  35549. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35550. vector.toArray(UniformBuffer._tempBuffer);
  35551. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35552. };
  35553. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35554. this._currentEffect.setVector4(name, vector);
  35555. };
  35556. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35557. vector.toArray(UniformBuffer._tempBuffer);
  35558. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35559. };
  35560. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35561. if (suffix === void 0) { suffix = ""; }
  35562. this._currentEffect.setColor3(name + suffix, color);
  35563. };
  35564. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35565. if (suffix === void 0) { suffix = ""; }
  35566. color.toArray(UniformBuffer._tempBuffer);
  35567. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35568. };
  35569. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35570. if (suffix === void 0) { suffix = ""; }
  35571. this._currentEffect.setColor4(name + suffix, color, alpha);
  35572. };
  35573. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35574. if (suffix === void 0) { suffix = ""; }
  35575. color.toArray(UniformBuffer._tempBuffer);
  35576. UniformBuffer._tempBuffer[3] = alpha;
  35577. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35578. };
  35579. /**
  35580. * Sets a sampler uniform on the effect.
  35581. * @param {string} name Name of the sampler.
  35582. * @param {Texture} texture
  35583. */
  35584. UniformBuffer.prototype.setTexture = function (name, texture) {
  35585. this._currentEffect.setTexture(name, texture);
  35586. };
  35587. /**
  35588. * Directly updates the value of the uniform in the cache AND on the GPU.
  35589. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35590. * @param {number[]|Float32Array} data Flattened data
  35591. */
  35592. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35593. this.updateUniform(uniformName, data, data.length);
  35594. this.update();
  35595. };
  35596. /**
  35597. * Binds this uniform buffer to an effect.
  35598. * @param {Effect} effect
  35599. * @param {string} name Name of the uniform block in the shader.
  35600. */
  35601. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35602. this._currentEffect = effect;
  35603. if (this._noUBO || !this._buffer) {
  35604. return;
  35605. }
  35606. effect.bindUniformBuffer(this._buffer, name);
  35607. };
  35608. /**
  35609. * Disposes the uniform buffer.
  35610. */
  35611. UniformBuffer.prototype.dispose = function () {
  35612. if (this._noUBO) {
  35613. return;
  35614. }
  35615. var index = this._engine._uniformBuffers.indexOf(this);
  35616. if (index !== -1) {
  35617. this._engine._uniformBuffers.splice(index, 1);
  35618. }
  35619. if (!this._buffer) {
  35620. return;
  35621. }
  35622. if (this._engine._releaseBuffer(this._buffer)) {
  35623. this._buffer = null;
  35624. }
  35625. };
  35626. // Pool for avoiding memory leaks
  35627. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35628. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35629. return UniformBuffer;
  35630. }());
  35631. BABYLON.UniformBuffer = UniformBuffer;
  35632. })(BABYLON || (BABYLON = {}));
  35633. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35634. var BABYLON;
  35635. (function (BABYLON) {
  35636. /**
  35637. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35638. */
  35639. var VertexData = /** @class */ (function () {
  35640. function VertexData() {
  35641. }
  35642. /**
  35643. * Uses the passed data array to set the set the values for the specified kind of data
  35644. * @param data a linear array of floating numbers
  35645. * @param kind the type of data that is being set, eg positions, colors etc
  35646. */
  35647. VertexData.prototype.set = function (data, kind) {
  35648. switch (kind) {
  35649. case BABYLON.VertexBuffer.PositionKind:
  35650. this.positions = data;
  35651. break;
  35652. case BABYLON.VertexBuffer.NormalKind:
  35653. this.normals = data;
  35654. break;
  35655. case BABYLON.VertexBuffer.TangentKind:
  35656. this.tangents = data;
  35657. break;
  35658. case BABYLON.VertexBuffer.UVKind:
  35659. this.uvs = data;
  35660. break;
  35661. case BABYLON.VertexBuffer.UV2Kind:
  35662. this.uvs2 = data;
  35663. break;
  35664. case BABYLON.VertexBuffer.UV3Kind:
  35665. this.uvs3 = data;
  35666. break;
  35667. case BABYLON.VertexBuffer.UV4Kind:
  35668. this.uvs4 = data;
  35669. break;
  35670. case BABYLON.VertexBuffer.UV5Kind:
  35671. this.uvs5 = data;
  35672. break;
  35673. case BABYLON.VertexBuffer.UV6Kind:
  35674. this.uvs6 = data;
  35675. break;
  35676. case BABYLON.VertexBuffer.ColorKind:
  35677. this.colors = data;
  35678. break;
  35679. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35680. this.matricesIndices = data;
  35681. break;
  35682. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35683. this.matricesWeights = data;
  35684. break;
  35685. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35686. this.matricesIndicesExtra = data;
  35687. break;
  35688. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35689. this.matricesWeightsExtra = data;
  35690. break;
  35691. }
  35692. };
  35693. /**
  35694. * Associates the vertexData to the passed Mesh.
  35695. * Sets it as updatable or not (default `false`)
  35696. * @param mesh the mesh the vertexData is applied to
  35697. * @param updatable when used and having the value true allows new data to update the vertexData
  35698. * @returns the VertexData
  35699. */
  35700. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35701. this._applyTo(mesh, updatable);
  35702. return this;
  35703. };
  35704. /**
  35705. * Associates the vertexData to the passed Geometry.
  35706. * Sets it as updatable or not (default `false`)
  35707. * @param geometry the geometry the vertexData is applied to
  35708. * @param updatable when used and having the value true allows new data to update the vertexData
  35709. * @returns VertexData
  35710. */
  35711. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35712. this._applyTo(geometry, updatable);
  35713. return this;
  35714. };
  35715. /**
  35716. * Updates the associated mesh
  35717. * @param mesh the mesh to be updated
  35718. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35719. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35720. * @returns VertexData
  35721. */
  35722. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35723. this._update(mesh);
  35724. return this;
  35725. };
  35726. /**
  35727. * Updates the associated geometry
  35728. * @param geometry the geometry to be updated
  35729. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35730. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35731. * @returns VertexData.
  35732. */
  35733. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35734. this._update(geometry);
  35735. return this;
  35736. };
  35737. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35738. if (updatable === void 0) { updatable = false; }
  35739. if (this.positions) {
  35740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35741. }
  35742. if (this.normals) {
  35743. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35744. }
  35745. if (this.tangents) {
  35746. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35747. }
  35748. if (this.uvs) {
  35749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35750. }
  35751. if (this.uvs2) {
  35752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35753. }
  35754. if (this.uvs3) {
  35755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35756. }
  35757. if (this.uvs4) {
  35758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35759. }
  35760. if (this.uvs5) {
  35761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35762. }
  35763. if (this.uvs6) {
  35764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35765. }
  35766. if (this.colors) {
  35767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35768. }
  35769. if (this.matricesIndices) {
  35770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35771. }
  35772. if (this.matricesWeights) {
  35773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35774. }
  35775. if (this.matricesIndicesExtra) {
  35776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35777. }
  35778. if (this.matricesWeightsExtra) {
  35779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35780. }
  35781. if (this.indices) {
  35782. meshOrGeometry.setIndices(this.indices, null, updatable);
  35783. }
  35784. return this;
  35785. };
  35786. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35787. if (this.positions) {
  35788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35789. }
  35790. if (this.normals) {
  35791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35792. }
  35793. if (this.tangents) {
  35794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35795. }
  35796. if (this.uvs) {
  35797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35798. }
  35799. if (this.uvs2) {
  35800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35801. }
  35802. if (this.uvs3) {
  35803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35804. }
  35805. if (this.uvs4) {
  35806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35807. }
  35808. if (this.uvs5) {
  35809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35810. }
  35811. if (this.uvs6) {
  35812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35813. }
  35814. if (this.colors) {
  35815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35816. }
  35817. if (this.matricesIndices) {
  35818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35819. }
  35820. if (this.matricesWeights) {
  35821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35822. }
  35823. if (this.matricesIndicesExtra) {
  35824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35825. }
  35826. if (this.matricesWeightsExtra) {
  35827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35828. }
  35829. if (this.indices) {
  35830. meshOrGeometry.setIndices(this.indices, null);
  35831. }
  35832. return this;
  35833. };
  35834. /**
  35835. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35836. * @param matrix the transforming matrix
  35837. * @returns the VertexData
  35838. */
  35839. VertexData.prototype.transform = function (matrix) {
  35840. var transformed = BABYLON.Vector3.Zero();
  35841. var index;
  35842. if (this.positions) {
  35843. var position = BABYLON.Vector3.Zero();
  35844. for (index = 0; index < this.positions.length; index += 3) {
  35845. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35846. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35847. this.positions[index] = transformed.x;
  35848. this.positions[index + 1] = transformed.y;
  35849. this.positions[index + 2] = transformed.z;
  35850. }
  35851. }
  35852. if (this.normals) {
  35853. var normal = BABYLON.Vector3.Zero();
  35854. for (index = 0; index < this.normals.length; index += 3) {
  35855. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35856. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35857. this.normals[index] = transformed.x;
  35858. this.normals[index + 1] = transformed.y;
  35859. this.normals[index + 2] = transformed.z;
  35860. }
  35861. }
  35862. if (this.tangents) {
  35863. var tangent = BABYLON.Vector4.Zero();
  35864. var tangentTransformed = BABYLON.Vector4.Zero();
  35865. for (index = 0; index < this.tangents.length; index += 4) {
  35866. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35867. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35868. this.tangents[index] = tangentTransformed.x;
  35869. this.tangents[index + 1] = tangentTransformed.y;
  35870. this.tangents[index + 2] = tangentTransformed.z;
  35871. this.tangents[index + 3] = tangentTransformed.w;
  35872. }
  35873. }
  35874. return this;
  35875. };
  35876. /**
  35877. * Merges the passed VertexData into the current one
  35878. * @param other the VertexData to be merged into the current one
  35879. * @returns the modified VertexData
  35880. */
  35881. VertexData.prototype.merge = function (other) {
  35882. this._validate();
  35883. other._validate();
  35884. if (!this.normals !== !other.normals ||
  35885. !this.tangents !== !other.tangents ||
  35886. !this.uvs !== !other.uvs ||
  35887. !this.uvs2 !== !other.uvs2 ||
  35888. !this.uvs3 !== !other.uvs3 ||
  35889. !this.uvs4 !== !other.uvs4 ||
  35890. !this.uvs5 !== !other.uvs5 ||
  35891. !this.uvs6 !== !other.uvs6 ||
  35892. !this.colors !== !other.colors ||
  35893. !this.matricesIndices !== !other.matricesIndices ||
  35894. !this.matricesWeights !== !other.matricesWeights ||
  35895. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35896. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35897. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35898. }
  35899. if (other.indices) {
  35900. if (!this.indices) {
  35901. this.indices = [];
  35902. }
  35903. var offset = this.positions ? this.positions.length / 3 : 0;
  35904. for (var index = 0; index < other.indices.length; index++) {
  35905. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35906. this.indices.push(other.indices[index] + offset);
  35907. }
  35908. }
  35909. this.positions = this._mergeElement(this.positions, other.positions);
  35910. this.normals = this._mergeElement(this.normals, other.normals);
  35911. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35912. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35913. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35914. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35915. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35916. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35917. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35918. this.colors = this._mergeElement(this.colors, other.colors);
  35919. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35920. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35921. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35922. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35923. return this;
  35924. };
  35925. VertexData.prototype._mergeElement = function (source, other) {
  35926. if (!source) {
  35927. return other;
  35928. }
  35929. if (!other) {
  35930. return source;
  35931. }
  35932. var len = other.length + source.length;
  35933. var isSrcTypedArray = source instanceof Float32Array;
  35934. var isOthTypedArray = other instanceof Float32Array;
  35935. // use non-loop method when the source is Float32Array
  35936. if (isSrcTypedArray) {
  35937. var ret32 = new Float32Array(len);
  35938. ret32.set(source);
  35939. ret32.set(other, source.length);
  35940. return ret32;
  35941. // source is number[], when other is also use concat
  35942. }
  35943. else if (!isOthTypedArray) {
  35944. return source.concat(other);
  35945. // source is a number[], but other is a Float32Array, loop required
  35946. }
  35947. else {
  35948. var ret = source.slice(0); // copy source to a separate array
  35949. for (var i = 0, len = other.length; i < len; i++) {
  35950. ret.push(other[i]);
  35951. }
  35952. return ret;
  35953. }
  35954. };
  35955. VertexData.prototype._validate = function () {
  35956. if (!this.positions) {
  35957. throw new Error("Positions are required");
  35958. }
  35959. var getElementCount = function (kind, values) {
  35960. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35961. if ((values.length % stride) !== 0) {
  35962. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35963. }
  35964. return values.length / stride;
  35965. };
  35966. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35967. var validateElementCount = function (kind, values) {
  35968. var elementCount = getElementCount(kind, values);
  35969. if (elementCount !== positionsElementCount) {
  35970. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35971. }
  35972. };
  35973. if (this.normals)
  35974. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35975. if (this.tangents)
  35976. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35977. if (this.uvs)
  35978. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35979. if (this.uvs2)
  35980. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35981. if (this.uvs3)
  35982. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35983. if (this.uvs4)
  35984. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35985. if (this.uvs5)
  35986. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35987. if (this.uvs6)
  35988. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35989. if (this.colors)
  35990. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35991. if (this.matricesIndices)
  35992. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35993. if (this.matricesWeights)
  35994. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35995. if (this.matricesIndicesExtra)
  35996. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35997. if (this.matricesWeightsExtra)
  35998. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35999. };
  36000. /**
  36001. * Serializes the VertexData
  36002. * @returns a serialized object
  36003. */
  36004. VertexData.prototype.serialize = function () {
  36005. var serializationObject = this.serialize();
  36006. if (this.positions) {
  36007. serializationObject.positions = this.positions;
  36008. }
  36009. if (this.normals) {
  36010. serializationObject.normals = this.normals;
  36011. }
  36012. if (this.tangents) {
  36013. serializationObject.tangents = this.tangents;
  36014. }
  36015. if (this.uvs) {
  36016. serializationObject.uvs = this.uvs;
  36017. }
  36018. if (this.uvs2) {
  36019. serializationObject.uvs2 = this.uvs2;
  36020. }
  36021. if (this.uvs3) {
  36022. serializationObject.uvs3 = this.uvs3;
  36023. }
  36024. if (this.uvs4) {
  36025. serializationObject.uvs4 = this.uvs4;
  36026. }
  36027. if (this.uvs5) {
  36028. serializationObject.uvs5 = this.uvs5;
  36029. }
  36030. if (this.uvs6) {
  36031. serializationObject.uvs6 = this.uvs6;
  36032. }
  36033. if (this.colors) {
  36034. serializationObject.colors = this.colors;
  36035. }
  36036. if (this.matricesIndices) {
  36037. serializationObject.matricesIndices = this.matricesIndices;
  36038. serializationObject.matricesIndices._isExpanded = true;
  36039. }
  36040. if (this.matricesWeights) {
  36041. serializationObject.matricesWeights = this.matricesWeights;
  36042. }
  36043. if (this.matricesIndicesExtra) {
  36044. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36045. serializationObject.matricesIndicesExtra._isExpanded = true;
  36046. }
  36047. if (this.matricesWeightsExtra) {
  36048. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36049. }
  36050. serializationObject.indices = this.indices;
  36051. return serializationObject;
  36052. };
  36053. // Statics
  36054. /**
  36055. * Extracts the vertexData from a mesh
  36056. * @param mesh the mesh from which to extract the VertexData
  36057. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36058. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36059. * @returns the object VertexData associated to the passed mesh
  36060. */
  36061. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36062. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36063. };
  36064. /**
  36065. * Extracts the vertexData from the geometry
  36066. * @param geometry the geometry from which to extract the VertexData
  36067. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36068. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36069. * @returns the object VertexData associated to the passed mesh
  36070. */
  36071. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36072. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36073. };
  36074. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36075. var result = new VertexData();
  36076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36077. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36078. }
  36079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36080. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36081. }
  36082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36083. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36084. }
  36085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36086. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36087. }
  36088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36089. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36090. }
  36091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36092. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36093. }
  36094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36095. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36096. }
  36097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36098. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36099. }
  36100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36101. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36102. }
  36103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36104. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36105. }
  36106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36107. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36108. }
  36109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36110. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36111. }
  36112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36113. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36114. }
  36115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36116. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36117. }
  36118. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36119. return result;
  36120. };
  36121. /**
  36122. * Creates the VertexData for a Ribbon
  36123. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36124. * * pathArray array of paths, each of which an array of successive Vector3
  36125. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36126. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36127. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36128. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36129. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36130. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36131. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36132. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36133. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36134. * @returns the VertexData of the ribbon
  36135. */
  36136. VertexData.CreateRibbon = function (options) {
  36137. var pathArray = options.pathArray;
  36138. var closeArray = options.closeArray || false;
  36139. var closePath = options.closePath || false;
  36140. var invertUV = options.invertUV || false;
  36141. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36142. var offset = options.offset || defaultOffset;
  36143. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36144. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36145. var customUV = options.uvs;
  36146. var customColors = options.colors;
  36147. var positions = [];
  36148. var indices = [];
  36149. var normals = [];
  36150. var uvs = [];
  36151. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36152. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36153. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36154. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36155. var minlg; // minimal length among all paths from pathArray
  36156. var lg = []; // array of path lengths : nb of vertex per path
  36157. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36158. var p; // path iterator
  36159. var i; // point iterator
  36160. var j; // point iterator
  36161. // if single path in pathArray
  36162. if (pathArray.length < 2) {
  36163. var ar1 = [];
  36164. var ar2 = [];
  36165. for (i = 0; i < pathArray[0].length - offset; i++) {
  36166. ar1.push(pathArray[0][i]);
  36167. ar2.push(pathArray[0][i + offset]);
  36168. }
  36169. pathArray = [ar1, ar2];
  36170. }
  36171. // positions and horizontal distances (u)
  36172. var idc = 0;
  36173. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36174. var path;
  36175. var l;
  36176. minlg = pathArray[0].length;
  36177. var vectlg;
  36178. var dist;
  36179. for (p = 0; p < pathArray.length; p++) {
  36180. uTotalDistance[p] = 0;
  36181. us[p] = [0];
  36182. path = pathArray[p];
  36183. l = path.length;
  36184. minlg = (minlg < l) ? minlg : l;
  36185. j = 0;
  36186. while (j < l) {
  36187. positions.push(path[j].x, path[j].y, path[j].z);
  36188. if (j > 0) {
  36189. vectlg = path[j].subtract(path[j - 1]).length();
  36190. dist = vectlg + uTotalDistance[p];
  36191. us[p].push(dist);
  36192. uTotalDistance[p] = dist;
  36193. }
  36194. j++;
  36195. }
  36196. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36197. j--;
  36198. positions.push(path[0].x, path[0].y, path[0].z);
  36199. vectlg = path[j].subtract(path[0]).length();
  36200. dist = vectlg + uTotalDistance[p];
  36201. us[p].push(dist);
  36202. uTotalDistance[p] = dist;
  36203. }
  36204. lg[p] = l + closePathCorr;
  36205. idx[p] = idc;
  36206. idc += (l + closePathCorr);
  36207. }
  36208. // vertical distances (v)
  36209. var path1;
  36210. var path2;
  36211. var vertex1 = null;
  36212. var vertex2 = null;
  36213. for (i = 0; i < minlg + closePathCorr; i++) {
  36214. vTotalDistance[i] = 0;
  36215. vs[i] = [0];
  36216. for (p = 0; p < pathArray.length - 1; p++) {
  36217. path1 = pathArray[p];
  36218. path2 = pathArray[p + 1];
  36219. if (i === minlg) { // closePath
  36220. vertex1 = path1[0];
  36221. vertex2 = path2[0];
  36222. }
  36223. else {
  36224. vertex1 = path1[i];
  36225. vertex2 = path2[i];
  36226. }
  36227. vectlg = vertex2.subtract(vertex1).length();
  36228. dist = vectlg + vTotalDistance[i];
  36229. vs[i].push(dist);
  36230. vTotalDistance[i] = dist;
  36231. }
  36232. if (closeArray && vertex2 && vertex1) {
  36233. path1 = pathArray[p];
  36234. path2 = pathArray[0];
  36235. if (i === minlg) { // closePath
  36236. vertex2 = path2[0];
  36237. }
  36238. vectlg = vertex2.subtract(vertex1).length();
  36239. dist = vectlg + vTotalDistance[i];
  36240. vTotalDistance[i] = dist;
  36241. }
  36242. }
  36243. // uvs
  36244. var u;
  36245. var v;
  36246. if (customUV) {
  36247. for (p = 0; p < customUV.length; p++) {
  36248. uvs.push(customUV[p].x, customUV[p].y);
  36249. }
  36250. }
  36251. else {
  36252. for (p = 0; p < pathArray.length; p++) {
  36253. for (i = 0; i < minlg + closePathCorr; i++) {
  36254. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36255. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36256. if (invertUV) {
  36257. uvs.push(v, u);
  36258. }
  36259. else {
  36260. uvs.push(u, v);
  36261. }
  36262. }
  36263. }
  36264. }
  36265. // indices
  36266. p = 0; // path index
  36267. var pi = 0; // positions array index
  36268. var l1 = lg[p] - 1; // path1 length
  36269. var l2 = lg[p + 1] - 1; // path2 length
  36270. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36271. var shft = idx[1] - idx[0]; // shift
  36272. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36273. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36274. // 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
  36275. indices.push(pi, pi + shft, pi + 1);
  36276. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36277. pi += 1;
  36278. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36279. p++;
  36280. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36281. shft = idx[0] - idx[p];
  36282. l1 = lg[p] - 1;
  36283. l2 = lg[0] - 1;
  36284. }
  36285. else {
  36286. shft = idx[p + 1] - idx[p];
  36287. l1 = lg[p] - 1;
  36288. l2 = lg[p + 1] - 1;
  36289. }
  36290. pi = idx[p];
  36291. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36292. }
  36293. }
  36294. // normals
  36295. VertexData.ComputeNormals(positions, indices, normals);
  36296. if (closePath) { // update both the first and last vertex normals to their average value
  36297. var indexFirst = 0;
  36298. var indexLast = 0;
  36299. for (p = 0; p < pathArray.length; p++) {
  36300. indexFirst = idx[p] * 3;
  36301. if (p + 1 < pathArray.length) {
  36302. indexLast = (idx[p + 1] - 1) * 3;
  36303. }
  36304. else {
  36305. indexLast = normals.length - 3;
  36306. }
  36307. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36308. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36309. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36310. normals[indexLast] = normals[indexFirst];
  36311. normals[indexLast + 1] = normals[indexFirst + 1];
  36312. normals[indexLast + 2] = normals[indexFirst + 2];
  36313. }
  36314. }
  36315. // sides
  36316. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36317. // Colors
  36318. var colors = null;
  36319. if (customColors) {
  36320. colors = new Float32Array(customColors.length * 4);
  36321. for (var c = 0; c < customColors.length; c++) {
  36322. colors[c * 4] = customColors[c].r;
  36323. colors[c * 4 + 1] = customColors[c].g;
  36324. colors[c * 4 + 2] = customColors[c].b;
  36325. colors[c * 4 + 3] = customColors[c].a;
  36326. }
  36327. }
  36328. // Result
  36329. var vertexData = new VertexData();
  36330. var positions32 = new Float32Array(positions);
  36331. var normals32 = new Float32Array(normals);
  36332. var uvs32 = new Float32Array(uvs);
  36333. vertexData.indices = indices;
  36334. vertexData.positions = positions32;
  36335. vertexData.normals = normals32;
  36336. vertexData.uvs = uvs32;
  36337. if (colors) {
  36338. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36339. }
  36340. if (closePath) {
  36341. vertexData._idx = idx;
  36342. }
  36343. return vertexData;
  36344. };
  36345. /**
  36346. * Creates the VertexData for a box
  36347. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36348. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36349. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36350. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36351. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36352. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36353. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36354. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36355. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36356. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36357. * @returns the VertexData of the box
  36358. */
  36359. VertexData.CreateBox = function (options) {
  36360. var normalsSource = [
  36361. new BABYLON.Vector3(0, 0, 1),
  36362. new BABYLON.Vector3(0, 0, -1),
  36363. new BABYLON.Vector3(1, 0, 0),
  36364. new BABYLON.Vector3(-1, 0, 0),
  36365. new BABYLON.Vector3(0, 1, 0),
  36366. new BABYLON.Vector3(0, -1, 0)
  36367. ];
  36368. var indices = [];
  36369. var positions = [];
  36370. var normals = [];
  36371. var uvs = [];
  36372. var width = options.width || options.size || 1;
  36373. var height = options.height || options.size || 1;
  36374. var depth = options.depth || options.size || 1;
  36375. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36376. var faceUV = options.faceUV || new Array(6);
  36377. var faceColors = options.faceColors;
  36378. var colors = [];
  36379. // default face colors and UV if undefined
  36380. for (var f = 0; f < 6; f++) {
  36381. if (faceUV[f] === undefined) {
  36382. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36383. }
  36384. if (faceColors && faceColors[f] === undefined) {
  36385. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36386. }
  36387. }
  36388. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36389. // Create each face in turn.
  36390. for (var index = 0; index < normalsSource.length; index++) {
  36391. var normal = normalsSource[index];
  36392. // Get two vectors perpendicular to the face normal and to each other.
  36393. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36394. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36395. // Six indices (two triangles) per face.
  36396. var verticesLength = positions.length / 3;
  36397. indices.push(verticesLength);
  36398. indices.push(verticesLength + 1);
  36399. indices.push(verticesLength + 2);
  36400. indices.push(verticesLength);
  36401. indices.push(verticesLength + 2);
  36402. indices.push(verticesLength + 3);
  36403. // Four vertices per face.
  36404. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36405. positions.push(vertex.x, vertex.y, vertex.z);
  36406. normals.push(normal.x, normal.y, normal.z);
  36407. uvs.push(faceUV[index].z, faceUV[index].w);
  36408. if (faceColors) {
  36409. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36410. }
  36411. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36412. positions.push(vertex.x, vertex.y, vertex.z);
  36413. normals.push(normal.x, normal.y, normal.z);
  36414. uvs.push(faceUV[index].x, faceUV[index].w);
  36415. if (faceColors) {
  36416. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36417. }
  36418. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36419. positions.push(vertex.x, vertex.y, vertex.z);
  36420. normals.push(normal.x, normal.y, normal.z);
  36421. uvs.push(faceUV[index].x, faceUV[index].y);
  36422. if (faceColors) {
  36423. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36424. }
  36425. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36426. positions.push(vertex.x, vertex.y, vertex.z);
  36427. normals.push(normal.x, normal.y, normal.z);
  36428. uvs.push(faceUV[index].z, faceUV[index].y);
  36429. if (faceColors) {
  36430. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36431. }
  36432. }
  36433. // sides
  36434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36435. // Result
  36436. var vertexData = new VertexData();
  36437. vertexData.indices = indices;
  36438. vertexData.positions = positions;
  36439. vertexData.normals = normals;
  36440. vertexData.uvs = uvs;
  36441. if (faceColors) {
  36442. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36443. vertexData.colors = totalColors;
  36444. }
  36445. return vertexData;
  36446. };
  36447. /**
  36448. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36449. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36450. * * segments sets the number of horizontal strips optional, default 32
  36451. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36452. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36453. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36454. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36455. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36456. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36457. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36458. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36459. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36460. * @returns the VertexData of the ellipsoid
  36461. */
  36462. VertexData.CreateSphere = function (options) {
  36463. var segments = options.segments || 32;
  36464. var diameterX = options.diameterX || options.diameter || 1;
  36465. var diameterY = options.diameterY || options.diameter || 1;
  36466. var diameterZ = options.diameterZ || options.diameter || 1;
  36467. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36468. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36469. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36470. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36471. var totalZRotationSteps = 2 + segments;
  36472. var totalYRotationSteps = 2 * totalZRotationSteps;
  36473. var indices = [];
  36474. var positions = [];
  36475. var normals = [];
  36476. var uvs = [];
  36477. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36478. var normalizedZ = zRotationStep / totalZRotationSteps;
  36479. var angleZ = normalizedZ * Math.PI * slice;
  36480. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36481. var normalizedY = yRotationStep / totalYRotationSteps;
  36482. var angleY = normalizedY * Math.PI * 2 * arc;
  36483. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36484. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36485. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36486. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36487. var vertex = complete.multiply(radius);
  36488. var normal = complete.divide(radius).normalize();
  36489. positions.push(vertex.x, vertex.y, vertex.z);
  36490. normals.push(normal.x, normal.y, normal.z);
  36491. uvs.push(normalizedY, normalizedZ);
  36492. }
  36493. if (zRotationStep > 0) {
  36494. var verticesCount = positions.length / 3;
  36495. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36496. indices.push((firstIndex));
  36497. indices.push((firstIndex + 1));
  36498. indices.push(firstIndex + totalYRotationSteps + 1);
  36499. indices.push((firstIndex + totalYRotationSteps + 1));
  36500. indices.push((firstIndex + 1));
  36501. indices.push((firstIndex + totalYRotationSteps + 2));
  36502. }
  36503. }
  36504. }
  36505. // Sides
  36506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36507. // Result
  36508. var vertexData = new VertexData();
  36509. vertexData.indices = indices;
  36510. vertexData.positions = positions;
  36511. vertexData.normals = normals;
  36512. vertexData.uvs = uvs;
  36513. return vertexData;
  36514. };
  36515. /**
  36516. * Creates the VertexData for a cylinder, cone or prism
  36517. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36518. * * height sets the height (y direction) of the cylinder, optional, default 2
  36519. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36520. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36521. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36522. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36523. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36524. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36525. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36526. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36527. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36528. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36529. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36530. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36531. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36532. * @returns the VertexData of the cylinder, cone or prism
  36533. */
  36534. VertexData.CreateCylinder = function (options) {
  36535. var height = options.height || 2;
  36536. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36537. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36538. var tessellation = options.tessellation || 24;
  36539. var subdivisions = options.subdivisions || 1;
  36540. var hasRings = options.hasRings ? true : false;
  36541. var enclose = options.enclose ? true : false;
  36542. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36543. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36544. var faceUV = options.faceUV || new Array(3);
  36545. var faceColors = options.faceColors;
  36546. // default face colors and UV if undefined
  36547. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36548. var ringNb = (hasRings) ? subdivisions : 1;
  36549. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36550. var f;
  36551. for (f = 0; f < surfaceNb; f++) {
  36552. if (faceColors && faceColors[f] === undefined) {
  36553. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36554. }
  36555. }
  36556. for (f = 0; f < surfaceNb; f++) {
  36557. if (faceUV && faceUV[f] === undefined) {
  36558. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36559. }
  36560. }
  36561. var indices = new Array();
  36562. var positions = new Array();
  36563. var normals = new Array();
  36564. var uvs = new Array();
  36565. var colors = new Array();
  36566. var angle_step = Math.PI * 2 * arc / tessellation;
  36567. var angle;
  36568. var h;
  36569. var radius;
  36570. var tan = (diameterBottom - diameterTop) / 2 / height;
  36571. var ringVertex = BABYLON.Vector3.Zero();
  36572. var ringNormal = BABYLON.Vector3.Zero();
  36573. var ringFirstVertex = BABYLON.Vector3.Zero();
  36574. var ringFirstNormal = BABYLON.Vector3.Zero();
  36575. var quadNormal = BABYLON.Vector3.Zero();
  36576. var Y = BABYLON.Axis.Y;
  36577. // positions, normals, uvs
  36578. var i;
  36579. var j;
  36580. var r;
  36581. var ringIdx = 1;
  36582. var s = 1; // surface index
  36583. var cs = 0;
  36584. var v = 0;
  36585. for (i = 0; i <= subdivisions; i++) {
  36586. h = i / subdivisions;
  36587. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36588. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36589. for (r = 0; r < ringIdx; r++) {
  36590. if (hasRings) {
  36591. s += r;
  36592. }
  36593. if (enclose) {
  36594. s += 2 * r;
  36595. }
  36596. for (j = 0; j <= tessellation; j++) {
  36597. angle = j * angle_step;
  36598. // position
  36599. ringVertex.x = Math.cos(-angle) * radius;
  36600. ringVertex.y = -height / 2 + h * height;
  36601. ringVertex.z = Math.sin(-angle) * radius;
  36602. // normal
  36603. if (diameterTop === 0 && i === subdivisions) {
  36604. // if no top cap, reuse former normals
  36605. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36606. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36607. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36608. }
  36609. else {
  36610. ringNormal.x = ringVertex.x;
  36611. ringNormal.z = ringVertex.z;
  36612. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36613. ringNormal.normalize();
  36614. }
  36615. // keep first ring vertex values for enclose
  36616. if (j === 0) {
  36617. ringFirstVertex.copyFrom(ringVertex);
  36618. ringFirstNormal.copyFrom(ringNormal);
  36619. }
  36620. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36621. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36622. if (hasRings) {
  36623. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36624. }
  36625. else {
  36626. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36627. }
  36628. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36629. if (faceColors) {
  36630. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36631. }
  36632. }
  36633. // if enclose, add four vertices and their dedicated normals
  36634. if (arc !== 1 && enclose) {
  36635. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36636. positions.push(0, ringVertex.y, 0);
  36637. positions.push(0, ringVertex.y, 0);
  36638. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36639. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36640. quadNormal.normalize();
  36641. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36642. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36643. quadNormal.normalize();
  36644. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36645. if (hasRings) {
  36646. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36647. }
  36648. else {
  36649. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36650. }
  36651. uvs.push(faceUV[s + 1].x, v);
  36652. uvs.push(faceUV[s + 1].z, v);
  36653. if (hasRings) {
  36654. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36655. }
  36656. else {
  36657. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36658. }
  36659. uvs.push(faceUV[s + 2].x, v);
  36660. uvs.push(faceUV[s + 2].z, v);
  36661. if (faceColors) {
  36662. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36663. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36664. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36665. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36666. }
  36667. }
  36668. if (cs !== s) {
  36669. cs = s;
  36670. }
  36671. }
  36672. }
  36673. // indices
  36674. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36675. var s;
  36676. i = 0;
  36677. for (s = 0; s < subdivisions; s++) {
  36678. var i0 = 0;
  36679. var i1 = 0;
  36680. var i2 = 0;
  36681. var i3 = 0;
  36682. for (j = 0; j < tessellation; j++) {
  36683. i0 = i * (e + 1) + j;
  36684. i1 = (i + 1) * (e + 1) + j;
  36685. i2 = i * (e + 1) + (j + 1);
  36686. i3 = (i + 1) * (e + 1) + (j + 1);
  36687. indices.push(i0, i1, i2);
  36688. indices.push(i3, i2, i1);
  36689. }
  36690. if (arc !== 1 && enclose) { // if enclose, add two quads
  36691. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36692. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36693. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36694. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36695. }
  36696. i = (hasRings) ? (i + 2) : (i + 1);
  36697. }
  36698. // Caps
  36699. var createCylinderCap = function (isTop) {
  36700. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36701. if (radius === 0) {
  36702. return;
  36703. }
  36704. // Cap positions, normals & uvs
  36705. var angle;
  36706. var circleVector;
  36707. var i;
  36708. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36709. var c = null;
  36710. if (faceColors) {
  36711. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36712. }
  36713. // cap center
  36714. var vbase = positions.length / 3;
  36715. var offset = isTop ? height / 2 : -height / 2;
  36716. var center = new BABYLON.Vector3(0, offset, 0);
  36717. positions.push(center.x, center.y, center.z);
  36718. normals.push(0, isTop ? 1 : -1, 0);
  36719. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36720. if (c) {
  36721. colors.push(c.r, c.g, c.b, c.a);
  36722. }
  36723. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36724. for (i = 0; i <= tessellation; i++) {
  36725. angle = Math.PI * 2 * i * arc / tessellation;
  36726. var cos = Math.cos(-angle);
  36727. var sin = Math.sin(-angle);
  36728. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36729. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36730. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36731. normals.push(0, isTop ? 1 : -1, 0);
  36732. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36733. if (c) {
  36734. colors.push(c.r, c.g, c.b, c.a);
  36735. }
  36736. }
  36737. // Cap indices
  36738. for (i = 0; i < tessellation; i++) {
  36739. if (!isTop) {
  36740. indices.push(vbase);
  36741. indices.push(vbase + (i + 1));
  36742. indices.push(vbase + (i + 2));
  36743. }
  36744. else {
  36745. indices.push(vbase);
  36746. indices.push(vbase + (i + 2));
  36747. indices.push(vbase + (i + 1));
  36748. }
  36749. }
  36750. };
  36751. // add caps to geometry
  36752. createCylinderCap(false);
  36753. createCylinderCap(true);
  36754. // Sides
  36755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36756. var vertexData = new VertexData();
  36757. vertexData.indices = indices;
  36758. vertexData.positions = positions;
  36759. vertexData.normals = normals;
  36760. vertexData.uvs = uvs;
  36761. if (faceColors) {
  36762. vertexData.colors = colors;
  36763. }
  36764. return vertexData;
  36765. };
  36766. /**
  36767. * Creates the VertexData for a torus
  36768. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36769. * * diameter the diameter of the torus, optional default 1
  36770. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36771. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36772. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36773. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36774. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36775. * @returns the VertexData of the torus
  36776. */
  36777. VertexData.CreateTorus = function (options) {
  36778. var indices = [];
  36779. var positions = [];
  36780. var normals = [];
  36781. var uvs = [];
  36782. var diameter = options.diameter || 1;
  36783. var thickness = options.thickness || 0.5;
  36784. var tessellation = options.tessellation || 16;
  36785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36786. var stride = tessellation + 1;
  36787. for (var i = 0; i <= tessellation; i++) {
  36788. var u = i / tessellation;
  36789. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36790. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36791. for (var j = 0; j <= tessellation; j++) {
  36792. var v = 1 - j / tessellation;
  36793. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36794. var dx = Math.cos(innerAngle);
  36795. var dy = Math.sin(innerAngle);
  36796. // Create a vertex.
  36797. var normal = new BABYLON.Vector3(dx, dy, 0);
  36798. var position = normal.scale(thickness / 2);
  36799. var textureCoordinate = new BABYLON.Vector2(u, v);
  36800. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36801. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36802. positions.push(position.x, position.y, position.z);
  36803. normals.push(normal.x, normal.y, normal.z);
  36804. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36805. // And create indices for two triangles.
  36806. var nextI = (i + 1) % stride;
  36807. var nextJ = (j + 1) % stride;
  36808. indices.push(i * stride + j);
  36809. indices.push(i * stride + nextJ);
  36810. indices.push(nextI * stride + j);
  36811. indices.push(i * stride + nextJ);
  36812. indices.push(nextI * stride + nextJ);
  36813. indices.push(nextI * stride + j);
  36814. }
  36815. }
  36816. // Sides
  36817. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36818. // Result
  36819. var vertexData = new VertexData();
  36820. vertexData.indices = indices;
  36821. vertexData.positions = positions;
  36822. vertexData.normals = normals;
  36823. vertexData.uvs = uvs;
  36824. return vertexData;
  36825. };
  36826. /**
  36827. * Creates the VertexData of the LineSystem
  36828. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36829. * - lines an array of lines, each line being an array of successive Vector3
  36830. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36831. * @returns the VertexData of the LineSystem
  36832. */
  36833. VertexData.CreateLineSystem = function (options) {
  36834. var indices = [];
  36835. var positions = [];
  36836. var lines = options.lines;
  36837. var colors = options.colors;
  36838. var vertexColors = [];
  36839. var idx = 0;
  36840. for (var l = 0; l < lines.length; l++) {
  36841. var points = lines[l];
  36842. for (var index = 0; index < points.length; index++) {
  36843. positions.push(points[index].x, points[index].y, points[index].z);
  36844. if (colors) {
  36845. var color = colors[l];
  36846. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36847. }
  36848. if (index > 0) {
  36849. indices.push(idx - 1);
  36850. indices.push(idx);
  36851. }
  36852. idx++;
  36853. }
  36854. }
  36855. var vertexData = new VertexData();
  36856. vertexData.indices = indices;
  36857. vertexData.positions = positions;
  36858. if (colors) {
  36859. vertexData.colors = vertexColors;
  36860. }
  36861. return vertexData;
  36862. };
  36863. /**
  36864. * Create the VertexData for a DashedLines
  36865. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36866. * - points an array successive Vector3
  36867. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36868. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36869. * - dashNb the intended total number of dashes, optional, default 200
  36870. * @returns the VertexData for the DashedLines
  36871. */
  36872. VertexData.CreateDashedLines = function (options) {
  36873. var dashSize = options.dashSize || 3;
  36874. var gapSize = options.gapSize || 1;
  36875. var dashNb = options.dashNb || 200;
  36876. var points = options.points;
  36877. var positions = new Array();
  36878. var indices = new Array();
  36879. var curvect = BABYLON.Vector3.Zero();
  36880. var lg = 0;
  36881. var nb = 0;
  36882. var shft = 0;
  36883. var dashshft = 0;
  36884. var curshft = 0;
  36885. var idx = 0;
  36886. var i = 0;
  36887. for (i = 0; i < points.length - 1; i++) {
  36888. points[i + 1].subtractToRef(points[i], curvect);
  36889. lg += curvect.length();
  36890. }
  36891. shft = lg / dashNb;
  36892. dashshft = dashSize * shft / (dashSize + gapSize);
  36893. for (i = 0; i < points.length - 1; i++) {
  36894. points[i + 1].subtractToRef(points[i], curvect);
  36895. nb = Math.floor(curvect.length() / shft);
  36896. curvect.normalize();
  36897. for (var j = 0; j < nb; j++) {
  36898. curshft = shft * j;
  36899. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36900. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36901. indices.push(idx, idx + 1);
  36902. idx += 2;
  36903. }
  36904. }
  36905. // Result
  36906. var vertexData = new VertexData();
  36907. vertexData.positions = positions;
  36908. vertexData.indices = indices;
  36909. return vertexData;
  36910. };
  36911. /**
  36912. * Creates the VertexData for a Ground
  36913. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36914. * - width the width (x direction) of the ground, optional, default 1
  36915. * - height the height (z direction) of the ground, optional, default 1
  36916. * - subdivisions the number of subdivisions per side, optional, default 1
  36917. * @returns the VertexData of the Ground
  36918. */
  36919. VertexData.CreateGround = function (options) {
  36920. var indices = [];
  36921. var positions = [];
  36922. var normals = [];
  36923. var uvs = [];
  36924. var row, col;
  36925. var width = options.width || 1;
  36926. var height = options.height || 1;
  36927. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36928. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36929. for (row = 0; row <= subdivisionsY; row++) {
  36930. for (col = 0; col <= subdivisionsX; col++) {
  36931. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36932. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36933. positions.push(position.x, position.y, position.z);
  36934. normals.push(normal.x, normal.y, normal.z);
  36935. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36936. }
  36937. }
  36938. for (row = 0; row < subdivisionsY; row++) {
  36939. for (col = 0; col < subdivisionsX; col++) {
  36940. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36941. indices.push(col + 1 + row * (subdivisionsX + 1));
  36942. indices.push(col + row * (subdivisionsX + 1));
  36943. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36944. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36945. indices.push(col + row * (subdivisionsX + 1));
  36946. }
  36947. }
  36948. // Result
  36949. var vertexData = new VertexData();
  36950. vertexData.indices = indices;
  36951. vertexData.positions = positions;
  36952. vertexData.normals = normals;
  36953. vertexData.uvs = uvs;
  36954. return vertexData;
  36955. };
  36956. /**
  36957. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36958. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36959. * * xmin the ground minimum X coordinate, optional, default -1
  36960. * * zmin the ground minimum Z coordinate, optional, default -1
  36961. * * xmax the ground maximum X coordinate, optional, default 1
  36962. * * zmax the ground maximum Z coordinate, optional, default 1
  36963. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  36964. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  36965. * @returns the VertexData of the TiledGround
  36966. */
  36967. VertexData.CreateTiledGround = function (options) {
  36968. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36969. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36970. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36971. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36972. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36973. var precision = options.precision || { w: 1, h: 1 };
  36974. var indices = new Array();
  36975. var positions = new Array();
  36976. var normals = new Array();
  36977. var uvs = new Array();
  36978. var row, col, tileRow, tileCol;
  36979. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36980. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36981. precision.w = (precision.w < 1) ? 1 : precision.w;
  36982. precision.h = (precision.h < 1) ? 1 : precision.h;
  36983. var tileSize = {
  36984. 'w': (xmax - xmin) / subdivisions.w,
  36985. 'h': (zmax - zmin) / subdivisions.h
  36986. };
  36987. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36988. // Indices
  36989. var base = positions.length / 3;
  36990. var rowLength = precision.w + 1;
  36991. for (row = 0; row < precision.h; row++) {
  36992. for (col = 0; col < precision.w; col++) {
  36993. var square = [
  36994. base + col + row * rowLength,
  36995. base + (col + 1) + row * rowLength,
  36996. base + (col + 1) + (row + 1) * rowLength,
  36997. base + col + (row + 1) * rowLength
  36998. ];
  36999. indices.push(square[1]);
  37000. indices.push(square[2]);
  37001. indices.push(square[3]);
  37002. indices.push(square[0]);
  37003. indices.push(square[1]);
  37004. indices.push(square[3]);
  37005. }
  37006. }
  37007. // Position, normals and uvs
  37008. var position = BABYLON.Vector3.Zero();
  37009. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37010. for (row = 0; row <= precision.h; row++) {
  37011. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37012. for (col = 0; col <= precision.w; col++) {
  37013. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37014. position.y = 0;
  37015. positions.push(position.x, position.y, position.z);
  37016. normals.push(normal.x, normal.y, normal.z);
  37017. uvs.push(col / precision.w, row / precision.h);
  37018. }
  37019. }
  37020. }
  37021. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37022. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37023. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37024. }
  37025. }
  37026. // Result
  37027. var vertexData = new VertexData();
  37028. vertexData.indices = indices;
  37029. vertexData.positions = positions;
  37030. vertexData.normals = normals;
  37031. vertexData.uvs = uvs;
  37032. return vertexData;
  37033. };
  37034. /**
  37035. * Creates the VertexData of the Ground designed from a heightmap
  37036. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37037. * * width the width (x direction) of the ground
  37038. * * height the height (z direction) of the ground
  37039. * * subdivisions the number of subdivisions per side
  37040. * * minHeight the minimum altitude on the ground, optional, default 0
  37041. * * maxHeight the maximum altitude on the ground, optional default 1
  37042. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37043. * * buffer the array holding the image color data
  37044. * * bufferWidth the width of image
  37045. * * bufferHeight the height of image
  37046. * @returns the VertexData of the Ground designed from a heightmap
  37047. */
  37048. VertexData.CreateGroundFromHeightMap = function (options) {
  37049. var indices = [];
  37050. var positions = [];
  37051. var normals = [];
  37052. var uvs = [];
  37053. var row, col;
  37054. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37055. // Vertices
  37056. for (row = 0; row <= options.subdivisions; row++) {
  37057. for (col = 0; col <= options.subdivisions; col++) {
  37058. 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));
  37059. // Compute height
  37060. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37061. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37062. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37063. var r = options.buffer[pos] / 255.0;
  37064. var g = options.buffer[pos + 1] / 255.0;
  37065. var b = options.buffer[pos + 2] / 255.0;
  37066. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37067. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37068. // Add vertex
  37069. positions.push(position.x, position.y, position.z);
  37070. normals.push(0, 0, 0);
  37071. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37072. }
  37073. }
  37074. // Indices
  37075. for (row = 0; row < options.subdivisions; row++) {
  37076. for (col = 0; col < options.subdivisions; col++) {
  37077. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37078. indices.push(col + 1 + row * (options.subdivisions + 1));
  37079. indices.push(col + row * (options.subdivisions + 1));
  37080. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37081. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37082. indices.push(col + row * (options.subdivisions + 1));
  37083. }
  37084. }
  37085. // Normals
  37086. VertexData.ComputeNormals(positions, indices, normals);
  37087. // Result
  37088. var vertexData = new VertexData();
  37089. vertexData.indices = indices;
  37090. vertexData.positions = positions;
  37091. vertexData.normals = normals;
  37092. vertexData.uvs = uvs;
  37093. return vertexData;
  37094. };
  37095. /**
  37096. * Creates the VertexData for a Plane
  37097. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37098. * * size sets the width and height of the plane to the value of size, optional default 1
  37099. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37100. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37101. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37102. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37103. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37104. * @returns the VertexData of the box
  37105. */
  37106. VertexData.CreatePlane = function (options) {
  37107. var indices = [];
  37108. var positions = [];
  37109. var normals = [];
  37110. var uvs = [];
  37111. var width = options.width || options.size || 1;
  37112. var height = options.height || options.size || 1;
  37113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37114. // Vertices
  37115. var halfWidth = width / 2.0;
  37116. var halfHeight = height / 2.0;
  37117. positions.push(-halfWidth, -halfHeight, 0);
  37118. normals.push(0, 0, -1.0);
  37119. uvs.push(0.0, 0.0);
  37120. positions.push(halfWidth, -halfHeight, 0);
  37121. normals.push(0, 0, -1.0);
  37122. uvs.push(1.0, 0.0);
  37123. positions.push(halfWidth, halfHeight, 0);
  37124. normals.push(0, 0, -1.0);
  37125. uvs.push(1.0, 1.0);
  37126. positions.push(-halfWidth, halfHeight, 0);
  37127. normals.push(0, 0, -1.0);
  37128. uvs.push(0.0, 1.0);
  37129. // Indices
  37130. indices.push(0);
  37131. indices.push(1);
  37132. indices.push(2);
  37133. indices.push(0);
  37134. indices.push(2);
  37135. indices.push(3);
  37136. // Sides
  37137. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37138. // Result
  37139. var vertexData = new VertexData();
  37140. vertexData.indices = indices;
  37141. vertexData.positions = positions;
  37142. vertexData.normals = normals;
  37143. vertexData.uvs = uvs;
  37144. return vertexData;
  37145. };
  37146. /**
  37147. * Creates the VertexData of the Disc or regular Polygon
  37148. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37149. * * radius the radius of the disc, optional default 0.5
  37150. * * tessellation the number of polygon sides, optional, default 64
  37151. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37152. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37153. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37154. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37155. * @returns the VertexData of the box
  37156. */
  37157. VertexData.CreateDisc = function (options) {
  37158. var positions = new Array();
  37159. var indices = new Array();
  37160. var normals = new Array();
  37161. var uvs = new Array();
  37162. var radius = options.radius || 0.5;
  37163. var tessellation = options.tessellation || 64;
  37164. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37165. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37166. // positions and uvs
  37167. positions.push(0, 0, 0); // disc center first
  37168. uvs.push(0.5, 0.5);
  37169. var theta = Math.PI * 2 * arc;
  37170. var step = theta / tessellation;
  37171. for (var a = 0; a < theta; a += step) {
  37172. var x = Math.cos(a);
  37173. var y = Math.sin(a);
  37174. var u = (x + 1) / 2;
  37175. var v = (1 - y) / 2;
  37176. positions.push(radius * x, radius * y, 0);
  37177. uvs.push(u, v);
  37178. }
  37179. if (arc === 1) {
  37180. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37181. uvs.push(uvs[2], uvs[3]);
  37182. }
  37183. //indices
  37184. var vertexNb = positions.length / 3;
  37185. for (var i = 1; i < vertexNb - 1; i++) {
  37186. indices.push(i + 1, 0, i);
  37187. }
  37188. // result
  37189. VertexData.ComputeNormals(positions, indices, normals);
  37190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37191. var vertexData = new VertexData();
  37192. vertexData.indices = indices;
  37193. vertexData.positions = positions;
  37194. vertexData.normals = normals;
  37195. vertexData.uvs = uvs;
  37196. return vertexData;
  37197. };
  37198. /**
  37199. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37200. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37201. * @param polygon a mesh built from polygonTriangulation.build()
  37202. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37203. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37204. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37205. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37206. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37207. * @returns the VertexData of the Polygon
  37208. */
  37209. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37210. var faceUV = fUV || new Array(3);
  37211. var faceColors = fColors;
  37212. var colors = [];
  37213. // default face colors and UV if undefined
  37214. for (var f = 0; f < 3; f++) {
  37215. if (faceUV[f] === undefined) {
  37216. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37217. }
  37218. if (faceColors && faceColors[f] === undefined) {
  37219. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37220. }
  37221. }
  37222. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37223. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37224. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37225. var indices = polygon.getIndices();
  37226. // set face colours and textures
  37227. var idx = 0;
  37228. var face = 0;
  37229. for (var index = 0; index < normals.length; index += 3) {
  37230. //Edge Face no. 1
  37231. if (Math.abs(normals[index + 1]) < 0.001) {
  37232. face = 1;
  37233. }
  37234. //Top Face no. 0
  37235. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37236. face = 0;
  37237. }
  37238. //Bottom Face no. 2
  37239. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37240. face = 2;
  37241. }
  37242. idx = index / 3;
  37243. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37244. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37245. if (faceColors) {
  37246. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37247. }
  37248. }
  37249. // sides
  37250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37251. // Result
  37252. var vertexData = new VertexData();
  37253. vertexData.indices = indices;
  37254. vertexData.positions = positions;
  37255. vertexData.normals = normals;
  37256. vertexData.uvs = uvs;
  37257. if (faceColors) {
  37258. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37259. vertexData.colors = totalColors;
  37260. }
  37261. return vertexData;
  37262. };
  37263. /**
  37264. * Creates the VertexData of the IcoSphere
  37265. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37266. * * radius the radius of the IcoSphere, optional default 1
  37267. * * radiusX allows stretching in the x direction, optional, default radius
  37268. * * radiusY allows stretching in the y direction, optional, default radius
  37269. * * radiusZ allows stretching in the z direction, optional, default radius
  37270. * * flat when true creates a flat shaded mesh, optional, default true
  37271. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37272. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37273. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37274. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37275. * @returns the VertexData of the IcoSphere
  37276. */
  37277. VertexData.CreateIcoSphere = function (options) {
  37278. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37279. var radius = options.radius || 1;
  37280. var flat = (options.flat === undefined) ? true : options.flat;
  37281. var subdivisions = options.subdivisions || 4;
  37282. var radiusX = options.radiusX || radius;
  37283. var radiusY = options.radiusY || radius;
  37284. var radiusZ = options.radiusZ || radius;
  37285. var t = (1 + Math.sqrt(5)) / 2;
  37286. // 12 vertex x,y,z
  37287. var ico_vertices = [
  37288. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37289. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37290. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37291. ];
  37292. // index of 3 vertex makes a face of icopshere
  37293. var ico_indices = [
  37294. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37295. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37296. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37297. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37298. ];
  37299. // vertex for uv have aliased position, not for UV
  37300. var vertices_unalias_id = [
  37301. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37302. // vertex alias
  37303. 0,
  37304. 2,
  37305. 3,
  37306. 3,
  37307. 3,
  37308. 4,
  37309. 7,
  37310. 8,
  37311. 9,
  37312. 9,
  37313. 10,
  37314. 11 // 23: B + 12
  37315. ];
  37316. // uv as integer step (not pixels !)
  37317. var ico_vertexuv = [
  37318. 5, 1, 3, 1, 6, 4, 0, 0,
  37319. 5, 3, 4, 2, 2, 2, 4, 0,
  37320. 2, 0, 1, 1, 6, 0, 6, 2,
  37321. // vertex alias (for same vertex on different faces)
  37322. 0, 4,
  37323. 3, 3,
  37324. 4, 4,
  37325. 3, 1,
  37326. 4, 2,
  37327. 4, 4,
  37328. 0, 2,
  37329. 1, 1,
  37330. 2, 2,
  37331. 3, 3,
  37332. 1, 3,
  37333. 2, 4 // 23: B + 12
  37334. ];
  37335. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37336. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37337. // First island of uv mapping
  37338. // v = 4h 3+ 2
  37339. // v = 3h 9+ 4
  37340. // v = 2h 9+ 5 B
  37341. // v = 1h 9 1 0
  37342. // v = 0h 3 8 7 A
  37343. // u = 0 1 2 3 4 5 6 *a
  37344. // Second island of uv mapping
  37345. // v = 4h 0+ B+ 4+
  37346. // v = 3h A+ 2+
  37347. // v = 2h 7+ 6 3+
  37348. // v = 1h 8+ 3+
  37349. // v = 0h
  37350. // u = 0 1 2 3 4 5 6 *a
  37351. // Face layout on texture UV mapping
  37352. // ============
  37353. // \ 4 /\ 16 / ======
  37354. // \ / \ / /\ 11 /
  37355. // \/ 7 \/ / \ /
  37356. // ======= / 10 \/
  37357. // /\ 17 /\ =======
  37358. // / \ / \ \ 15 /\
  37359. // / 8 \/ 12 \ \ / \
  37360. // ============ \/ 6 \
  37361. // \ 18 /\ ============
  37362. // \ / \ \ 5 /\ 0 /
  37363. // \/ 13 \ \ / \ /
  37364. // ======= \/ 1 \/
  37365. // =============
  37366. // /\ 19 /\ 2 /\
  37367. // / \ / \ / \
  37368. // / 14 \/ 9 \/ 3 \
  37369. // ===================
  37370. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37371. var ustep = 138 / 1024;
  37372. var vstep = 239 / 1024;
  37373. var uoffset = 60 / 1024;
  37374. var voffset = 26 / 1024;
  37375. // Second island should have margin, not to touch the first island
  37376. // avoid any borderline artefact in pixel rounding
  37377. var island_u_offset = -40 / 1024;
  37378. var island_v_offset = +20 / 1024;
  37379. // face is either island 0 or 1 :
  37380. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37381. var island = [
  37382. 0, 0, 0, 0, 1,
  37383. 0, 0, 1, 1, 0,
  37384. 0, 0, 1, 1, 0,
  37385. 0, 1, 1, 1, 0 // 15 - 19
  37386. ];
  37387. var indices = new Array();
  37388. var positions = new Array();
  37389. var normals = new Array();
  37390. var uvs = new Array();
  37391. var current_indice = 0;
  37392. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37393. var face_vertex_pos = new Array(3);
  37394. var face_vertex_uv = new Array(3);
  37395. var v012;
  37396. for (v012 = 0; v012 < 3; v012++) {
  37397. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37398. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37399. }
  37400. // create all with normals
  37401. for (var face = 0; face < 20; face++) {
  37402. // 3 vertex per face
  37403. for (v012 = 0; v012 < 3; v012++) {
  37404. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37405. var v_id = ico_indices[3 * face + v012];
  37406. // vertex have 3D position (x,y,z)
  37407. 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]);
  37408. // Normalize to get normal, then scale to radius
  37409. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37410. // uv Coordinates from vertex ID
  37411. 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);
  37412. }
  37413. // Subdivide the face (interpolate pos, norm, uv)
  37414. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37415. // - norm is linear interpolation of vertex corner normal
  37416. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37417. // - uv is linear interpolation
  37418. //
  37419. // Topology is as below for sub-divide by 2
  37420. // vertex shown as v0,v1,v2
  37421. // interp index is i1 to progress in range [v0,v1[
  37422. // interp index is i2 to progress in range [v0,v2[
  37423. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37424. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37425. //
  37426. //
  37427. // i2 v2
  37428. // ^ ^
  37429. // / / \
  37430. // / / \
  37431. // / / \
  37432. // / / (0,1) \
  37433. // / #---------\
  37434. // / / \ (0,0)'/ \
  37435. // / / \ / \
  37436. // / / \ / \
  37437. // / / (0,0) \ / (1,0) \
  37438. // / #---------#---------\
  37439. // v0 v1
  37440. //
  37441. // --------------------> i1
  37442. //
  37443. // interp of (i1,i2):
  37444. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37445. // along i1 : lerp(x0,x1, i1/(S-i2))
  37446. //
  37447. // centroid of triangle is needed to get help normal computation
  37448. // (c1,c2) are used for centroid location
  37449. var interp_vertex = function (i1, i2, c1, c2) {
  37450. // vertex is interpolated from
  37451. // - face_vertex_pos[0..2]
  37452. // - face_vertex_uv[0..2]
  37453. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37454. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37455. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37456. pos_interp.normalize();
  37457. var vertex_normal;
  37458. if (flat) {
  37459. // in flat mode, recalculate normal as face centroid normal
  37460. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37461. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37462. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37463. }
  37464. else {
  37465. // in smooth mode, recalculate normal from each single vertex position
  37466. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37467. }
  37468. // Vertex normal need correction due to X,Y,Z radius scaling
  37469. vertex_normal.x /= radiusX;
  37470. vertex_normal.y /= radiusY;
  37471. vertex_normal.z /= radiusZ;
  37472. vertex_normal.normalize();
  37473. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37474. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37475. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37476. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37477. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37478. uvs.push(uv_interp.x, uv_interp.y);
  37479. // push each vertex has member of a face
  37480. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37481. indices.push(current_indice);
  37482. current_indice++;
  37483. };
  37484. for (var i2 = 0; i2 < subdivisions; i2++) {
  37485. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37486. // face : (i1,i2) for /\ :
  37487. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37488. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37489. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37490. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37491. if (i1 + i2 + 1 < subdivisions) {
  37492. // face : (i1,i2)' for \/ :
  37493. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37494. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37495. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37496. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37497. }
  37498. }
  37499. }
  37500. }
  37501. // Sides
  37502. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37503. // Result
  37504. var vertexData = new VertexData();
  37505. vertexData.indices = indices;
  37506. vertexData.positions = positions;
  37507. vertexData.normals = normals;
  37508. vertexData.uvs = uvs;
  37509. return vertexData;
  37510. };
  37511. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37512. /**
  37513. * Creates the VertexData for a Polyhedron
  37514. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37515. * * type provided types are:
  37516. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37517. * * 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)
  37518. * * size the size of the IcoSphere, optional default 1
  37519. * * sizeX allows stretching in the x direction, optional, default size
  37520. * * sizeY allows stretching in the y direction, optional, default size
  37521. * * sizeZ allows stretching in the z direction, optional, default size
  37522. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37523. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37524. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37525. * * flat when true creates a flat shaded mesh, optional, default true
  37526. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37527. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37528. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37529. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37530. * @returns the VertexData of the Polyhedron
  37531. */
  37532. VertexData.CreatePolyhedron = function (options) {
  37533. // provided polyhedron types :
  37534. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37535. // 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)
  37536. var polyhedra = [];
  37537. 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]] };
  37538. 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]] };
  37539. polyhedra[2] = {
  37540. 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]],
  37541. 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]]
  37542. };
  37543. polyhedra[3] = {
  37544. 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]],
  37545. 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]]
  37546. };
  37547. polyhedra[4] = {
  37548. 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]],
  37549. 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]]
  37550. };
  37551. 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]] };
  37552. 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]] };
  37553. 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]] };
  37554. 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]] };
  37555. 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]] };
  37556. 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]] };
  37557. 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]] };
  37558. 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]] };
  37559. 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]] };
  37560. polyhedra[14] = {
  37561. 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]],
  37562. 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]]
  37563. };
  37564. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37565. var size = options.size;
  37566. var sizeX = options.sizeX || size || 1;
  37567. var sizeY = options.sizeY || size || 1;
  37568. var sizeZ = options.sizeZ || size || 1;
  37569. var data = options.custom || polyhedra[type];
  37570. var nbfaces = data.face.length;
  37571. var faceUV = options.faceUV || new Array(nbfaces);
  37572. var faceColors = options.faceColors;
  37573. var flat = (options.flat === undefined) ? true : options.flat;
  37574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37575. var positions = new Array();
  37576. var indices = new Array();
  37577. var normals = new Array();
  37578. var uvs = new Array();
  37579. var colors = new Array();
  37580. var index = 0;
  37581. var faceIdx = 0; // face cursor in the array "indexes"
  37582. var indexes = new Array();
  37583. var i = 0;
  37584. var f = 0;
  37585. var u, v, ang, x, y, tmp;
  37586. // default face colors and UV if undefined
  37587. if (flat) {
  37588. for (f = 0; f < nbfaces; f++) {
  37589. if (faceColors && faceColors[f] === undefined) {
  37590. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37591. }
  37592. if (faceUV && faceUV[f] === undefined) {
  37593. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37594. }
  37595. }
  37596. }
  37597. if (!flat) {
  37598. for (i = 0; i < data.vertex.length; i++) {
  37599. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37600. uvs.push(0, 0);
  37601. }
  37602. for (f = 0; f < nbfaces; f++) {
  37603. for (i = 0; i < data.face[f].length - 2; i++) {
  37604. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37605. }
  37606. }
  37607. }
  37608. else {
  37609. for (f = 0; f < nbfaces; f++) {
  37610. var fl = data.face[f].length; // number of vertices of the current face
  37611. ang = 2 * Math.PI / fl;
  37612. x = 0.5 * Math.tan(ang / 2);
  37613. y = 0.5;
  37614. // positions, uvs, colors
  37615. for (i = 0; i < fl; i++) {
  37616. // positions
  37617. 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);
  37618. indexes.push(index);
  37619. index++;
  37620. // uvs
  37621. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37622. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37623. uvs.push(u, v);
  37624. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37625. y = x * Math.sin(ang) + y * Math.cos(ang);
  37626. x = tmp;
  37627. // colors
  37628. if (faceColors) {
  37629. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37630. }
  37631. }
  37632. // indices from indexes
  37633. for (i = 0; i < fl - 2; i++) {
  37634. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37635. }
  37636. faceIdx += fl;
  37637. }
  37638. }
  37639. VertexData.ComputeNormals(positions, indices, normals);
  37640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37641. var vertexData = new VertexData();
  37642. vertexData.positions = positions;
  37643. vertexData.indices = indices;
  37644. vertexData.normals = normals;
  37645. vertexData.uvs = uvs;
  37646. if (faceColors && flat) {
  37647. vertexData.colors = colors;
  37648. }
  37649. return vertexData;
  37650. };
  37651. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37652. /**
  37653. * Creates the VertexData for a TorusKnot
  37654. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37655. * * radius the radius of the torus knot, optional, default 2
  37656. * * tube the thickness of the tube, optional, default 0.5
  37657. * * radialSegments the number of sides on each tube segments, optional, default 32
  37658. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37659. * * p the number of windings around the z axis, optional, default 2
  37660. * * q the number of windings around the x axis, optional, default 3
  37661. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37662. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37663. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37664. * @returns the VertexData of the Torus Knot
  37665. */
  37666. VertexData.CreateTorusKnot = function (options) {
  37667. var indices = new Array();
  37668. var positions = new Array();
  37669. var normals = new Array();
  37670. var uvs = new Array();
  37671. var radius = options.radius || 2;
  37672. var tube = options.tube || 0.5;
  37673. var radialSegments = options.radialSegments || 32;
  37674. var tubularSegments = options.tubularSegments || 32;
  37675. var p = options.p || 2;
  37676. var q = options.q || 3;
  37677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37678. // Helper
  37679. var getPos = function (angle) {
  37680. var cu = Math.cos(angle);
  37681. var su = Math.sin(angle);
  37682. var quOverP = q / p * angle;
  37683. var cs = Math.cos(quOverP);
  37684. var tx = radius * (2 + cs) * 0.5 * cu;
  37685. var ty = radius * (2 + cs) * su * 0.5;
  37686. var tz = radius * Math.sin(quOverP) * 0.5;
  37687. return new BABYLON.Vector3(tx, ty, tz);
  37688. };
  37689. // Vertices
  37690. var i;
  37691. var j;
  37692. for (i = 0; i <= radialSegments; i++) {
  37693. var modI = i % radialSegments;
  37694. var u = modI / radialSegments * 2 * p * Math.PI;
  37695. var p1 = getPos(u);
  37696. var p2 = getPos(u + 0.01);
  37697. var tang = p2.subtract(p1);
  37698. var n = p2.add(p1);
  37699. var bitan = BABYLON.Vector3.Cross(tang, n);
  37700. n = BABYLON.Vector3.Cross(bitan, tang);
  37701. bitan.normalize();
  37702. n.normalize();
  37703. for (j = 0; j < tubularSegments; j++) {
  37704. var modJ = j % tubularSegments;
  37705. var v = modJ / tubularSegments * 2 * Math.PI;
  37706. var cx = -tube * Math.cos(v);
  37707. var cy = tube * Math.sin(v);
  37708. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37709. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37710. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37711. uvs.push(i / radialSegments);
  37712. uvs.push(j / tubularSegments);
  37713. }
  37714. }
  37715. for (i = 0; i < radialSegments; i++) {
  37716. for (j = 0; j < tubularSegments; j++) {
  37717. var jNext = (j + 1) % tubularSegments;
  37718. var a = i * tubularSegments + j;
  37719. var b = (i + 1) * tubularSegments + j;
  37720. var c = (i + 1) * tubularSegments + jNext;
  37721. var d = i * tubularSegments + jNext;
  37722. indices.push(d);
  37723. indices.push(b);
  37724. indices.push(a);
  37725. indices.push(d);
  37726. indices.push(c);
  37727. indices.push(b);
  37728. }
  37729. }
  37730. // Normals
  37731. VertexData.ComputeNormals(positions, indices, normals);
  37732. // Sides
  37733. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37734. // Result
  37735. var vertexData = new VertexData();
  37736. vertexData.indices = indices;
  37737. vertexData.positions = positions;
  37738. vertexData.normals = normals;
  37739. vertexData.uvs = uvs;
  37740. return vertexData;
  37741. };
  37742. // Tools
  37743. /**
  37744. * Compute normals for given positions and indices
  37745. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37746. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37747. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37748. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37749. * * facetNormals : optional array of facet normals (vector3)
  37750. * * facetPositions : optional array of facet positions (vector3)
  37751. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37752. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37753. * * bInfo : optional bounding info, required for facetPartitioning computation
  37754. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37755. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37756. * * useRightHandedSystem: optional boolean to for right handed system computation
  37757. * * depthSort : optional boolean to enable the facet depth sort computation
  37758. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37759. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37760. */
  37761. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37762. // temporary scalar variables
  37763. var index = 0; // facet index
  37764. var p1p2x = 0.0; // p1p2 vector x coordinate
  37765. var p1p2y = 0.0; // p1p2 vector y coordinate
  37766. var p1p2z = 0.0; // p1p2 vector z coordinate
  37767. var p3p2x = 0.0; // p3p2 vector x coordinate
  37768. var p3p2y = 0.0; // p3p2 vector y coordinate
  37769. var p3p2z = 0.0; // p3p2 vector z coordinate
  37770. var faceNormalx = 0.0; // facet normal x coordinate
  37771. var faceNormaly = 0.0; // facet normal y coordinate
  37772. var faceNormalz = 0.0; // facet normal z coordinate
  37773. var length = 0.0; // facet normal length before normalization
  37774. var v1x = 0; // vector1 x index in the positions array
  37775. var v1y = 0; // vector1 y index in the positions array
  37776. var v1z = 0; // vector1 z index in the positions array
  37777. var v2x = 0; // vector2 x index in the positions array
  37778. var v2y = 0; // vector2 y index in the positions array
  37779. var v2z = 0; // vector2 z index in the positions array
  37780. var v3x = 0; // vector3 x index in the positions array
  37781. var v3y = 0; // vector3 y index in the positions array
  37782. var v3z = 0; // vector3 z index in the positions array
  37783. var computeFacetNormals = false;
  37784. var computeFacetPositions = false;
  37785. var computeFacetPartitioning = false;
  37786. var computeDepthSort = false;
  37787. var faceNormalSign = 1;
  37788. var ratio = 0;
  37789. var distanceTo = null;
  37790. if (options) {
  37791. computeFacetNormals = (options.facetNormals) ? true : false;
  37792. computeFacetPositions = (options.facetPositions) ? true : false;
  37793. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37794. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37795. ratio = options.ratio || 0;
  37796. computeDepthSort = (options.depthSort) ? true : false;
  37797. distanceTo = (options.distanceTo);
  37798. if (computeDepthSort) {
  37799. if (distanceTo === undefined) {
  37800. distanceTo = BABYLON.Vector3.Zero();
  37801. }
  37802. var depthSortedFacets = options.depthSortedFacets;
  37803. }
  37804. }
  37805. // facetPartitioning reinit if needed
  37806. var xSubRatio = 0;
  37807. var ySubRatio = 0;
  37808. var zSubRatio = 0;
  37809. var subSq = 0;
  37810. if (computeFacetPartitioning && options && options.bbSize) {
  37811. var ox = 0; // X partitioning index for facet position
  37812. var oy = 0; // Y partinioning index for facet position
  37813. var oz = 0; // Z partinioning index for facet position
  37814. var b1x = 0; // X partitioning index for facet v1 vertex
  37815. var b1y = 0; // Y partitioning index for facet v1 vertex
  37816. var b1z = 0; // z partitioning index for facet v1 vertex
  37817. var b2x = 0; // X partitioning index for facet v2 vertex
  37818. var b2y = 0; // Y partitioning index for facet v2 vertex
  37819. var b2z = 0; // Z partitioning index for facet v2 vertex
  37820. var b3x = 0; // X partitioning index for facet v3 vertex
  37821. var b3y = 0; // Y partitioning index for facet v3 vertex
  37822. var b3z = 0; // Z partitioning index for facet v3 vertex
  37823. var block_idx_o = 0; // facet barycenter block index
  37824. var block_idx_v1 = 0; // v1 vertex block index
  37825. var block_idx_v2 = 0; // v2 vertex block index
  37826. var block_idx_v3 = 0; // v3 vertex block index
  37827. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37828. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37829. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37830. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37831. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37832. subSq = options.subDiv.max * options.subDiv.max;
  37833. options.facetPartitioning.length = 0;
  37834. }
  37835. // reset the normals
  37836. for (index = 0; index < positions.length; index++) {
  37837. normals[index] = 0.0;
  37838. }
  37839. // Loop : 1 indice triplet = 1 facet
  37840. var nbFaces = (indices.length / 3) | 0;
  37841. for (index = 0; index < nbFaces; index++) {
  37842. // get the indexes of the coordinates of each vertex of the facet
  37843. v1x = indices[index * 3] * 3;
  37844. v1y = v1x + 1;
  37845. v1z = v1x + 2;
  37846. v2x = indices[index * 3 + 1] * 3;
  37847. v2y = v2x + 1;
  37848. v2z = v2x + 2;
  37849. v3x = indices[index * 3 + 2] * 3;
  37850. v3y = v3x + 1;
  37851. v3z = v3x + 2;
  37852. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37853. p1p2y = positions[v1y] - positions[v2y];
  37854. p1p2z = positions[v1z] - positions[v2z];
  37855. p3p2x = positions[v3x] - positions[v2x];
  37856. p3p2y = positions[v3y] - positions[v2y];
  37857. p3p2z = positions[v3z] - positions[v2z];
  37858. // compute the face normal with the cross product
  37859. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37860. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37861. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37862. // normalize this normal and store it in the array facetData
  37863. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37864. length = (length === 0) ? 1.0 : length;
  37865. faceNormalx /= length;
  37866. faceNormaly /= length;
  37867. faceNormalz /= length;
  37868. if (computeFacetNormals && options) {
  37869. options.facetNormals[index].x = faceNormalx;
  37870. options.facetNormals[index].y = faceNormaly;
  37871. options.facetNormals[index].z = faceNormalz;
  37872. }
  37873. if (computeFacetPositions && options) {
  37874. // compute and the facet barycenter coordinates in the array facetPositions
  37875. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37876. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37877. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37878. }
  37879. if (computeFacetPartitioning && options) {
  37880. // store the facet indexes in arrays in the main facetPartitioning array :
  37881. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37882. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37883. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37884. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37885. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37886. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37887. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37888. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37889. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37890. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37891. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37892. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37893. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37894. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37895. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37896. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37897. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37898. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37899. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37900. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37901. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37902. // push each facet index in each block containing the vertex
  37903. options.facetPartitioning[block_idx_v1].push(index);
  37904. if (block_idx_v2 != block_idx_v1) {
  37905. options.facetPartitioning[block_idx_v2].push(index);
  37906. }
  37907. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37908. options.facetPartitioning[block_idx_v3].push(index);
  37909. }
  37910. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37911. options.facetPartitioning[block_idx_o].push(index);
  37912. }
  37913. }
  37914. if (computeDepthSort && options && options.facetPositions) {
  37915. var dsf = depthSortedFacets[index];
  37916. dsf.ind = index * 3;
  37917. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37918. }
  37919. // compute the normals anyway
  37920. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37921. normals[v1y] += faceNormaly;
  37922. normals[v1z] += faceNormalz;
  37923. normals[v2x] += faceNormalx;
  37924. normals[v2y] += faceNormaly;
  37925. normals[v2z] += faceNormalz;
  37926. normals[v3x] += faceNormalx;
  37927. normals[v3y] += faceNormaly;
  37928. normals[v3z] += faceNormalz;
  37929. }
  37930. // last normalization of each normal
  37931. for (index = 0; index < normals.length / 3; index++) {
  37932. faceNormalx = normals[index * 3];
  37933. faceNormaly = normals[index * 3 + 1];
  37934. faceNormalz = normals[index * 3 + 2];
  37935. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37936. length = (length === 0) ? 1.0 : length;
  37937. faceNormalx /= length;
  37938. faceNormaly /= length;
  37939. faceNormalz /= length;
  37940. normals[index * 3] = faceNormalx;
  37941. normals[index * 3 + 1] = faceNormaly;
  37942. normals[index * 3 + 2] = faceNormalz;
  37943. }
  37944. };
  37945. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37946. var li = indices.length;
  37947. var ln = normals.length;
  37948. var i;
  37949. var n;
  37950. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37951. switch (sideOrientation) {
  37952. case BABYLON.Mesh.FRONTSIDE:
  37953. // nothing changed
  37954. break;
  37955. case BABYLON.Mesh.BACKSIDE:
  37956. var tmp;
  37957. // indices
  37958. for (i = 0; i < li; i += 3) {
  37959. tmp = indices[i];
  37960. indices[i] = indices[i + 2];
  37961. indices[i + 2] = tmp;
  37962. }
  37963. // normals
  37964. for (n = 0; n < ln; n++) {
  37965. normals[n] = -normals[n];
  37966. }
  37967. break;
  37968. case BABYLON.Mesh.DOUBLESIDE:
  37969. // positions
  37970. var lp = positions.length;
  37971. var l = lp / 3;
  37972. for (var p = 0; p < lp; p++) {
  37973. positions[lp + p] = positions[p];
  37974. }
  37975. // indices
  37976. for (i = 0; i < li; i += 3) {
  37977. indices[i + li] = indices[i + 2] + l;
  37978. indices[i + 1 + li] = indices[i + 1] + l;
  37979. indices[i + 2 + li] = indices[i] + l;
  37980. }
  37981. // normals
  37982. for (n = 0; n < ln; n++) {
  37983. normals[ln + n] = -normals[n];
  37984. }
  37985. // uvs
  37986. var lu = uvs.length;
  37987. var u = 0;
  37988. for (u = 0; u < lu; u++) {
  37989. uvs[u + lu] = uvs[u];
  37990. }
  37991. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37992. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37993. u = 0;
  37994. for (i = 0; i < lu / 2; i++) {
  37995. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37996. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37997. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37998. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37999. u += 2;
  38000. }
  38001. break;
  38002. }
  38003. };
  38004. /**
  38005. * Applies VertexData created from the imported parameters to the geometry
  38006. * @param parsedVertexData the parsed data from an imported file
  38007. * @param geometry the geometry to apply the VertexData to
  38008. */
  38009. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38010. var vertexData = new VertexData();
  38011. // positions
  38012. var positions = parsedVertexData.positions;
  38013. if (positions) {
  38014. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38015. }
  38016. // normals
  38017. var normals = parsedVertexData.normals;
  38018. if (normals) {
  38019. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38020. }
  38021. // tangents
  38022. var tangents = parsedVertexData.tangents;
  38023. if (tangents) {
  38024. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38025. }
  38026. // uvs
  38027. var uvs = parsedVertexData.uvs;
  38028. if (uvs) {
  38029. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38030. }
  38031. // uv2s
  38032. var uv2s = parsedVertexData.uv2s;
  38033. if (uv2s) {
  38034. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38035. }
  38036. // uv3s
  38037. var uv3s = parsedVertexData.uv3s;
  38038. if (uv3s) {
  38039. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38040. }
  38041. // uv4s
  38042. var uv4s = parsedVertexData.uv4s;
  38043. if (uv4s) {
  38044. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38045. }
  38046. // uv5s
  38047. var uv5s = parsedVertexData.uv5s;
  38048. if (uv5s) {
  38049. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38050. }
  38051. // uv6s
  38052. var uv6s = parsedVertexData.uv6s;
  38053. if (uv6s) {
  38054. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38055. }
  38056. // colors
  38057. var colors = parsedVertexData.colors;
  38058. if (colors) {
  38059. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38060. }
  38061. // matricesIndices
  38062. var matricesIndices = parsedVertexData.matricesIndices;
  38063. if (matricesIndices) {
  38064. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38065. }
  38066. // matricesWeights
  38067. var matricesWeights = parsedVertexData.matricesWeights;
  38068. if (matricesWeights) {
  38069. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38070. }
  38071. // indices
  38072. var indices = parsedVertexData.indices;
  38073. if (indices) {
  38074. vertexData.indices = indices;
  38075. }
  38076. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38077. };
  38078. return VertexData;
  38079. }());
  38080. BABYLON.VertexData = VertexData;
  38081. })(BABYLON || (BABYLON = {}));
  38082. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38083. var BABYLON;
  38084. (function (BABYLON) {
  38085. /**
  38086. * Class used to store geometry data (vertex buffers + index buffer)
  38087. */
  38088. var Geometry = /** @class */ (function () {
  38089. /**
  38090. * Creates a new geometry
  38091. * @param id defines the unique ID
  38092. * @param scene defines the hosting scene
  38093. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38094. * @param updatable defines if geometry must be updatable (false by default)
  38095. * @param mesh defines the mesh that will be associated with the geometry
  38096. */
  38097. function Geometry(id, scene, vertexData, updatable, mesh) {
  38098. if (updatable === void 0) { updatable = false; }
  38099. if (mesh === void 0) { mesh = null; }
  38100. /**
  38101. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38102. */
  38103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38104. this._totalVertices = 0;
  38105. this._isDisposed = false;
  38106. this._indexBufferIsUpdatable = false;
  38107. this.id = id;
  38108. this._engine = scene.getEngine();
  38109. this._meshes = [];
  38110. this._scene = scene;
  38111. //Init vertex buffer cache
  38112. this._vertexBuffers = {};
  38113. this._indices = [];
  38114. this._updatable = updatable;
  38115. // vertexData
  38116. if (vertexData) {
  38117. this.setAllVerticesData(vertexData, updatable);
  38118. }
  38119. else {
  38120. this._totalVertices = 0;
  38121. this._indices = [];
  38122. }
  38123. if (this._engine.getCaps().vertexArrayObject) {
  38124. this._vertexArrayObjects = {};
  38125. }
  38126. // applyToMesh
  38127. if (mesh) {
  38128. if (mesh.getClassName() === "LinesMesh") {
  38129. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38130. this._updateExtend();
  38131. }
  38132. this.applyToMesh(mesh);
  38133. mesh.computeWorldMatrix(true);
  38134. }
  38135. }
  38136. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38137. /**
  38138. * 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
  38139. */
  38140. get: function () {
  38141. return this._boundingBias;
  38142. },
  38143. /**
  38144. * 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
  38145. */
  38146. set: function (value) {
  38147. if (this._boundingBias && this._boundingBias.equals(value)) {
  38148. return;
  38149. }
  38150. this._boundingBias = value.clone();
  38151. this._updateBoundingInfo(true, null);
  38152. },
  38153. enumerable: true,
  38154. configurable: true
  38155. });
  38156. /**
  38157. * Static function used to attach a new empty geometry to a mesh
  38158. * @param mesh defines the mesh to attach the geometry to
  38159. * @returns the new {BABYLON.Geometry}
  38160. */
  38161. Geometry.CreateGeometryForMesh = function (mesh) {
  38162. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38163. geometry.applyToMesh(mesh);
  38164. return geometry;
  38165. };
  38166. Object.defineProperty(Geometry.prototype, "extend", {
  38167. /**
  38168. * Gets the current extend of the geometry
  38169. */
  38170. get: function () {
  38171. return this._extend;
  38172. },
  38173. enumerable: true,
  38174. configurable: true
  38175. });
  38176. /**
  38177. * Gets the hosting scene
  38178. * @returns the hosting {BABYLON.Scene}
  38179. */
  38180. Geometry.prototype.getScene = function () {
  38181. return this._scene;
  38182. };
  38183. /**
  38184. * Gets the hosting engine
  38185. * @returns the hosting {BABYLON.Engine}
  38186. */
  38187. Geometry.prototype.getEngine = function () {
  38188. return this._engine;
  38189. };
  38190. /**
  38191. * Defines if the geometry is ready to use
  38192. * @returns true if the geometry is ready to be used
  38193. */
  38194. Geometry.prototype.isReady = function () {
  38195. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38196. };
  38197. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38198. /**
  38199. * Gets a value indicating that the geometry should not be serialized
  38200. */
  38201. get: function () {
  38202. for (var index = 0; index < this._meshes.length; index++) {
  38203. if (!this._meshes[index].doNotSerialize) {
  38204. return false;
  38205. }
  38206. }
  38207. return true;
  38208. },
  38209. enumerable: true,
  38210. configurable: true
  38211. });
  38212. /** @ignore */
  38213. Geometry.prototype._rebuild = function () {
  38214. if (this._vertexArrayObjects) {
  38215. this._vertexArrayObjects = {};
  38216. }
  38217. // Index buffer
  38218. if (this._meshes.length !== 0 && this._indices) {
  38219. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38220. }
  38221. // Vertex buffers
  38222. for (var key in this._vertexBuffers) {
  38223. var vertexBuffer = this._vertexBuffers[key];
  38224. vertexBuffer._rebuild();
  38225. }
  38226. };
  38227. /**
  38228. * Affects all gemetry data in one call
  38229. * @param vertexData defines the geometry data
  38230. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38231. */
  38232. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38233. vertexData.applyToGeometry(this, updatable);
  38234. this.notifyUpdate();
  38235. };
  38236. /**
  38237. * Set specific vertex data
  38238. * @param kind defines the data kind (Position, normal, etc...)
  38239. * @param data defines the vertex data to use
  38240. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38241. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38242. */
  38243. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38244. if (updatable === void 0) { updatable = false; }
  38245. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38246. this.setVerticesBuffer(buffer);
  38247. };
  38248. /**
  38249. * Removes a specific vertex data
  38250. * @param kind defines the data kind (Position, normal, etc...)
  38251. */
  38252. Geometry.prototype.removeVerticesData = function (kind) {
  38253. if (this._vertexBuffers[kind]) {
  38254. this._vertexBuffers[kind].dispose();
  38255. delete this._vertexBuffers[kind];
  38256. }
  38257. };
  38258. /**
  38259. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38260. * @param buffer defines the vertex buffer to use
  38261. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38262. */
  38263. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38264. if (totalVertices === void 0) { totalVertices = null; }
  38265. var kind = buffer.getKind();
  38266. if (this._vertexBuffers[kind]) {
  38267. this._vertexBuffers[kind].dispose();
  38268. }
  38269. this._vertexBuffers[kind] = buffer;
  38270. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38271. var data = buffer.getData();
  38272. if (totalVertices != null) {
  38273. this._totalVertices = totalVertices;
  38274. }
  38275. else {
  38276. if (data != null) {
  38277. this._totalVertices = data.length / (buffer.byteStride / 4);
  38278. }
  38279. }
  38280. this._updateExtend(data);
  38281. this._resetPointsArrayCache();
  38282. var meshes = this._meshes;
  38283. var numOfMeshes = meshes.length;
  38284. for (var index = 0; index < numOfMeshes; index++) {
  38285. var mesh = meshes[index];
  38286. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38287. mesh._createGlobalSubMesh(false);
  38288. mesh.computeWorldMatrix(true);
  38289. }
  38290. }
  38291. this.notifyUpdate(kind);
  38292. if (this._vertexArrayObjects) {
  38293. this._disposeVertexArrayObjects();
  38294. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38295. }
  38296. };
  38297. /**
  38298. * Update a specific vertex buffer
  38299. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38300. * It will do nothing if the buffer is not updatable
  38301. * @param kind defines the data kind (Position, normal, etc...)
  38302. * @param data defines the data to use
  38303. * @param offset defines the offset in the target buffer where to store the data
  38304. * @param useBytes set to true if the offset is in bytes
  38305. */
  38306. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38307. if (useBytes === void 0) { useBytes = false; }
  38308. var vertexBuffer = this.getVertexBuffer(kind);
  38309. if (!vertexBuffer) {
  38310. return;
  38311. }
  38312. vertexBuffer.updateDirectly(data, offset, useBytes);
  38313. this.notifyUpdate(kind);
  38314. };
  38315. /**
  38316. * Update a specific vertex buffer
  38317. * This function will create a new buffer if the current one is not updatable
  38318. * @param kind defines the data kind (Position, normal, etc...)
  38319. * @param data defines the data to use
  38320. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38321. */
  38322. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38323. if (updateExtends === void 0) { updateExtends = false; }
  38324. var vertexBuffer = this.getVertexBuffer(kind);
  38325. if (!vertexBuffer) {
  38326. return;
  38327. }
  38328. vertexBuffer.update(data);
  38329. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38330. this._updateBoundingInfo(updateExtends, data);
  38331. }
  38332. this.notifyUpdate(kind);
  38333. };
  38334. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38335. if (updateExtends) {
  38336. this._updateExtend(data);
  38337. }
  38338. var meshes = this._meshes;
  38339. var numOfMeshes = meshes.length;
  38340. this._resetPointsArrayCache();
  38341. for (var index = 0; index < numOfMeshes; index++) {
  38342. var mesh = meshes[index];
  38343. if (updateExtends) {
  38344. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38346. var subMesh = mesh.subMeshes[subIndex];
  38347. subMesh.refreshBoundingInfo();
  38348. }
  38349. }
  38350. }
  38351. };
  38352. /** @ignore */
  38353. Geometry.prototype._bind = function (effect, indexToBind) {
  38354. if (!effect) {
  38355. return;
  38356. }
  38357. if (indexToBind === undefined) {
  38358. indexToBind = this._indexBuffer;
  38359. }
  38360. var vbs = this.getVertexBuffers();
  38361. if (!vbs) {
  38362. return;
  38363. }
  38364. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38365. this._engine.bindBuffers(vbs, indexToBind, effect);
  38366. return;
  38367. }
  38368. // Using VAO
  38369. if (!this._vertexArrayObjects[effect.key]) {
  38370. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38371. }
  38372. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38373. };
  38374. /**
  38375. * Gets total number of vertices
  38376. * @returns the total number of vertices
  38377. */
  38378. Geometry.prototype.getTotalVertices = function () {
  38379. if (!this.isReady()) {
  38380. return 0;
  38381. }
  38382. return this._totalVertices;
  38383. };
  38384. /**
  38385. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38386. * @param kind defines the data kind (Position, normal, etc...)
  38387. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38388. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38389. * @returns a float array containing vertex data
  38390. */
  38391. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38392. var vertexBuffer = this.getVertexBuffer(kind);
  38393. if (!vertexBuffer) {
  38394. return null;
  38395. }
  38396. var data = vertexBuffer.getData();
  38397. if (!data) {
  38398. return null;
  38399. }
  38400. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38401. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38402. var count = this._totalVertices * defaultStride;
  38403. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38404. var copy_1 = new Array(count);
  38405. vertexBuffer.forEach(count, function (value, index) {
  38406. copy_1[index] = value;
  38407. });
  38408. return copy_1;
  38409. }
  38410. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38411. if (data instanceof Array) {
  38412. var offset = vertexBuffer.byteOffset / 4;
  38413. return BABYLON.Tools.Slice(data, offset, offset + count);
  38414. }
  38415. else if (data instanceof ArrayBuffer) {
  38416. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38417. }
  38418. else {
  38419. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38420. }
  38421. }
  38422. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38423. return BABYLON.Tools.Slice(data);
  38424. }
  38425. return data;
  38426. };
  38427. /**
  38428. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38429. * @param kind defines the data kind (Position, normal, etc...)
  38430. * @returns true if the vertex buffer with the specified kind is updatable
  38431. */
  38432. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38433. var vb = this._vertexBuffers[kind];
  38434. if (!vb) {
  38435. return false;
  38436. }
  38437. return vb.isUpdatable();
  38438. };
  38439. /**
  38440. * Gets a specific vertex buffer
  38441. * @param kind defines the data kind (Position, normal, etc...)
  38442. * @returns a {BABYLON.VertexBuffer}
  38443. */
  38444. Geometry.prototype.getVertexBuffer = function (kind) {
  38445. if (!this.isReady()) {
  38446. return null;
  38447. }
  38448. return this._vertexBuffers[kind];
  38449. };
  38450. /**
  38451. * Returns all vertex buffers
  38452. * @return an object holding all vertex buffers indexed by kind
  38453. */
  38454. Geometry.prototype.getVertexBuffers = function () {
  38455. if (!this.isReady()) {
  38456. return null;
  38457. }
  38458. return this._vertexBuffers;
  38459. };
  38460. /**
  38461. * Gets a boolean indicating if specific vertex buffer is present
  38462. * @param kind defines the data kind (Position, normal, etc...)
  38463. * @returns true if data is present
  38464. */
  38465. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38466. if (!this._vertexBuffers) {
  38467. if (this._delayInfo) {
  38468. return this._delayInfo.indexOf(kind) !== -1;
  38469. }
  38470. return false;
  38471. }
  38472. return this._vertexBuffers[kind] !== undefined;
  38473. };
  38474. /**
  38475. * Gets a list of all attached data kinds (Position, normal, etc...)
  38476. * @returns a list of string containing all kinds
  38477. */
  38478. Geometry.prototype.getVerticesDataKinds = function () {
  38479. var result = [];
  38480. var kind;
  38481. if (!this._vertexBuffers && this._delayInfo) {
  38482. for (kind in this._delayInfo) {
  38483. result.push(kind);
  38484. }
  38485. }
  38486. else {
  38487. for (kind in this._vertexBuffers) {
  38488. result.push(kind);
  38489. }
  38490. }
  38491. return result;
  38492. };
  38493. /**
  38494. * Update index buffer
  38495. * @param indices defines the indices to store in the index buffer
  38496. * @param offset defines the offset in the target buffer where to store the data
  38497. */
  38498. Geometry.prototype.updateIndices = function (indices, offset) {
  38499. if (!this._indexBuffer) {
  38500. return;
  38501. }
  38502. if (!this._indexBufferIsUpdatable) {
  38503. this.setIndices(indices, null, true);
  38504. }
  38505. else {
  38506. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38507. }
  38508. };
  38509. /**
  38510. * Creates a new index buffer
  38511. * @param indices defines the indices to store in the index buffer
  38512. * @param totalVertices defines the total number of vertices (could be null)
  38513. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38514. */
  38515. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38516. if (totalVertices === void 0) { totalVertices = null; }
  38517. if (updatable === void 0) { updatable = false; }
  38518. if (this._indexBuffer) {
  38519. this._engine._releaseBuffer(this._indexBuffer);
  38520. }
  38521. this._disposeVertexArrayObjects();
  38522. this._indices = indices;
  38523. this._indexBufferIsUpdatable = updatable;
  38524. if (this._meshes.length !== 0 && this._indices) {
  38525. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38526. }
  38527. if (totalVertices != undefined) { // including null and undefined
  38528. this._totalVertices = totalVertices;
  38529. }
  38530. var meshes = this._meshes;
  38531. var numOfMeshes = meshes.length;
  38532. for (var index = 0; index < numOfMeshes; index++) {
  38533. meshes[index]._createGlobalSubMesh(true);
  38534. }
  38535. this.notifyUpdate();
  38536. };
  38537. /**
  38538. * Return the total number of indices
  38539. * @returns the total number of indices
  38540. */
  38541. Geometry.prototype.getTotalIndices = function () {
  38542. if (!this.isReady()) {
  38543. return 0;
  38544. }
  38545. return this._indices.length;
  38546. };
  38547. /**
  38548. * Gets the index buffer array
  38549. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38550. * @returns the index buffer array
  38551. */
  38552. Geometry.prototype.getIndices = function (copyWhenShared) {
  38553. if (!this.isReady()) {
  38554. return null;
  38555. }
  38556. var orig = this._indices;
  38557. if (!copyWhenShared || this._meshes.length === 1) {
  38558. return orig;
  38559. }
  38560. else {
  38561. var len = orig.length;
  38562. var copy = [];
  38563. for (var i = 0; i < len; i++) {
  38564. copy.push(orig[i]);
  38565. }
  38566. return copy;
  38567. }
  38568. };
  38569. /**
  38570. * Gets the index buffer
  38571. * @return the index buffer
  38572. */
  38573. Geometry.prototype.getIndexBuffer = function () {
  38574. if (!this.isReady()) {
  38575. return null;
  38576. }
  38577. return this._indexBuffer;
  38578. };
  38579. /** @ignore */
  38580. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38581. if (effect === void 0) { effect = null; }
  38582. if (!effect || !this._vertexArrayObjects) {
  38583. return;
  38584. }
  38585. if (this._vertexArrayObjects[effect.key]) {
  38586. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38587. delete this._vertexArrayObjects[effect.key];
  38588. }
  38589. };
  38590. /**
  38591. * Release the associated resources for a specific mesh
  38592. * @param mesh defines the source mesh
  38593. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38594. */
  38595. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38596. var meshes = this._meshes;
  38597. var index = meshes.indexOf(mesh);
  38598. if (index === -1) {
  38599. return;
  38600. }
  38601. meshes.splice(index, 1);
  38602. mesh._geometry = null;
  38603. if (meshes.length === 0 && shouldDispose) {
  38604. this.dispose();
  38605. }
  38606. };
  38607. /**
  38608. * Apply current geometry to a given mesh
  38609. * @param mesh defines the mesh to apply geometry to
  38610. */
  38611. Geometry.prototype.applyToMesh = function (mesh) {
  38612. if (mesh._geometry === this) {
  38613. return;
  38614. }
  38615. var previousGeometry = mesh._geometry;
  38616. if (previousGeometry) {
  38617. previousGeometry.releaseForMesh(mesh);
  38618. }
  38619. var meshes = this._meshes;
  38620. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38621. mesh._geometry = this;
  38622. this._scene.pushGeometry(this);
  38623. meshes.push(mesh);
  38624. if (this.isReady()) {
  38625. this._applyToMesh(mesh);
  38626. }
  38627. else {
  38628. mesh._boundingInfo = this._boundingInfo;
  38629. }
  38630. };
  38631. Geometry.prototype._updateExtend = function (data) {
  38632. if (data === void 0) { data = null; }
  38633. if (!data) {
  38634. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38635. }
  38636. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38637. };
  38638. Geometry.prototype._applyToMesh = function (mesh) {
  38639. var numOfMeshes = this._meshes.length;
  38640. // vertexBuffers
  38641. for (var kind in this._vertexBuffers) {
  38642. if (numOfMeshes === 1) {
  38643. this._vertexBuffers[kind].create();
  38644. }
  38645. var buffer = this._vertexBuffers[kind].getBuffer();
  38646. if (buffer)
  38647. buffer.references = numOfMeshes;
  38648. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38649. if (!this._extend) {
  38650. this._updateExtend();
  38651. }
  38652. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38653. mesh._createGlobalSubMesh(false);
  38654. //bounding info was just created again, world matrix should be applied again.
  38655. mesh._updateBoundingInfo();
  38656. }
  38657. }
  38658. // indexBuffer
  38659. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38660. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38661. }
  38662. if (this._indexBuffer) {
  38663. this._indexBuffer.references = numOfMeshes;
  38664. }
  38665. };
  38666. Geometry.prototype.notifyUpdate = function (kind) {
  38667. if (this.onGeometryUpdated) {
  38668. this.onGeometryUpdated(this, kind);
  38669. }
  38670. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38671. var mesh = _a[_i];
  38672. mesh._markSubMeshesAsAttributesDirty();
  38673. }
  38674. };
  38675. /**
  38676. * Load the geometry if it was flagged as delay loaded
  38677. * @param scene defines the hosting scene
  38678. * @param onLoaded defines a callback called when the geometry is loaded
  38679. */
  38680. Geometry.prototype.load = function (scene, onLoaded) {
  38681. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38682. return;
  38683. }
  38684. if (this.isReady()) {
  38685. if (onLoaded) {
  38686. onLoaded();
  38687. }
  38688. return;
  38689. }
  38690. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38691. this._queueLoad(scene, onLoaded);
  38692. };
  38693. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38694. var _this = this;
  38695. if (!this.delayLoadingFile) {
  38696. return;
  38697. }
  38698. scene._addPendingData(this);
  38699. scene._loadFile(this.delayLoadingFile, function (data) {
  38700. if (!_this._delayLoadingFunction) {
  38701. return;
  38702. }
  38703. _this._delayLoadingFunction(JSON.parse(data), _this);
  38704. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38705. _this._delayInfo = [];
  38706. scene._removePendingData(_this);
  38707. var meshes = _this._meshes;
  38708. var numOfMeshes = meshes.length;
  38709. for (var index = 0; index < numOfMeshes; index++) {
  38710. _this._applyToMesh(meshes[index]);
  38711. }
  38712. if (onLoaded) {
  38713. onLoaded();
  38714. }
  38715. }, undefined, true);
  38716. };
  38717. /**
  38718. * Invert the geometry to move from a right handed system to a left handed one.
  38719. */
  38720. Geometry.prototype.toLeftHanded = function () {
  38721. // Flip faces
  38722. var tIndices = this.getIndices(false);
  38723. if (tIndices != null && tIndices.length > 0) {
  38724. for (var i = 0; i < tIndices.length; i += 3) {
  38725. var tTemp = tIndices[i + 0];
  38726. tIndices[i + 0] = tIndices[i + 2];
  38727. tIndices[i + 2] = tTemp;
  38728. }
  38729. this.setIndices(tIndices);
  38730. }
  38731. // Negate position.z
  38732. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38733. if (tPositions != null && tPositions.length > 0) {
  38734. for (var i = 0; i < tPositions.length; i += 3) {
  38735. tPositions[i + 2] = -tPositions[i + 2];
  38736. }
  38737. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38738. }
  38739. // Negate normal.z
  38740. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38741. if (tNormals != null && tNormals.length > 0) {
  38742. for (var i = 0; i < tNormals.length; i += 3) {
  38743. tNormals[i + 2] = -tNormals[i + 2];
  38744. }
  38745. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38746. }
  38747. };
  38748. // Cache
  38749. /** @ignore */
  38750. Geometry.prototype._resetPointsArrayCache = function () {
  38751. this._positions = null;
  38752. };
  38753. /** @ignore */
  38754. Geometry.prototype._generatePointsArray = function () {
  38755. if (this._positions)
  38756. return true;
  38757. this._positions = [];
  38758. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38759. if (!data) {
  38760. return false;
  38761. }
  38762. for (var index = 0; index < data.length; index += 3) {
  38763. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38764. }
  38765. return true;
  38766. };
  38767. /**
  38768. * Gets a value indicating if the geometry is disposed
  38769. * @returns true if the geometry was disposed
  38770. */
  38771. Geometry.prototype.isDisposed = function () {
  38772. return this._isDisposed;
  38773. };
  38774. Geometry.prototype._disposeVertexArrayObjects = function () {
  38775. if (this._vertexArrayObjects) {
  38776. for (var kind in this._vertexArrayObjects) {
  38777. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38778. }
  38779. this._vertexArrayObjects = {};
  38780. }
  38781. };
  38782. /**
  38783. * Free all associated resources
  38784. */
  38785. Geometry.prototype.dispose = function () {
  38786. var meshes = this._meshes;
  38787. var numOfMeshes = meshes.length;
  38788. var index;
  38789. for (index = 0; index < numOfMeshes; index++) {
  38790. this.releaseForMesh(meshes[index]);
  38791. }
  38792. this._meshes = [];
  38793. this._disposeVertexArrayObjects();
  38794. for (var kind in this._vertexBuffers) {
  38795. this._vertexBuffers[kind].dispose();
  38796. }
  38797. this._vertexBuffers = {};
  38798. this._totalVertices = 0;
  38799. if (this._indexBuffer) {
  38800. this._engine._releaseBuffer(this._indexBuffer);
  38801. }
  38802. this._indexBuffer = null;
  38803. this._indices = [];
  38804. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38805. this.delayLoadingFile = null;
  38806. this._delayLoadingFunction = null;
  38807. this._delayInfo = [];
  38808. this._boundingInfo = null;
  38809. this._scene.removeGeometry(this);
  38810. this._isDisposed = true;
  38811. };
  38812. /**
  38813. * Clone the current geometry into a new geometry
  38814. * @param id defines the unique ID of the new geometry
  38815. * @returns a new geometry object
  38816. */
  38817. Geometry.prototype.copy = function (id) {
  38818. var vertexData = new BABYLON.VertexData();
  38819. vertexData.indices = [];
  38820. var indices = this.getIndices();
  38821. if (indices) {
  38822. for (var index = 0; index < indices.length; index++) {
  38823. vertexData.indices.push(indices[index]);
  38824. }
  38825. }
  38826. var updatable = false;
  38827. var stopChecking = false;
  38828. var kind;
  38829. for (kind in this._vertexBuffers) {
  38830. // using slice() to make a copy of the array and not just reference it
  38831. var data = this.getVerticesData(kind);
  38832. if (data instanceof Float32Array) {
  38833. vertexData.set(new Float32Array(data), kind);
  38834. }
  38835. else {
  38836. vertexData.set(data.slice(0), kind);
  38837. }
  38838. if (!stopChecking) {
  38839. var vb = this.getVertexBuffer(kind);
  38840. if (vb) {
  38841. updatable = vb.isUpdatable();
  38842. stopChecking = !updatable;
  38843. }
  38844. }
  38845. }
  38846. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38847. geometry.delayLoadState = this.delayLoadState;
  38848. geometry.delayLoadingFile = this.delayLoadingFile;
  38849. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38850. for (kind in this._delayInfo) {
  38851. geometry._delayInfo = geometry._delayInfo || [];
  38852. geometry._delayInfo.push(kind);
  38853. }
  38854. // Bounding info
  38855. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38856. return geometry;
  38857. };
  38858. /**
  38859. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38860. * @return a JSON representation of the current geometry data (without the vertices data)
  38861. */
  38862. Geometry.prototype.serialize = function () {
  38863. var serializationObject = {};
  38864. serializationObject.id = this.id;
  38865. serializationObject.updatable = this._updatable;
  38866. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38867. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38868. }
  38869. return serializationObject;
  38870. };
  38871. Geometry.prototype.toNumberArray = function (origin) {
  38872. if (Array.isArray(origin)) {
  38873. return origin;
  38874. }
  38875. else {
  38876. return Array.prototype.slice.call(origin);
  38877. }
  38878. };
  38879. /**
  38880. * Serialize all vertices data into a JSON oject
  38881. * @returns a JSON representation of the current geometry data
  38882. */
  38883. Geometry.prototype.serializeVerticeData = function () {
  38884. var serializationObject = this.serialize();
  38885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38886. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38887. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38888. serializationObject.positions._updatable = true;
  38889. }
  38890. }
  38891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38892. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38893. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38894. serializationObject.normals._updatable = true;
  38895. }
  38896. }
  38897. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38898. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38899. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38900. serializationObject.tangets._updatable = true;
  38901. }
  38902. }
  38903. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38904. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38905. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38906. serializationObject.uvs._updatable = true;
  38907. }
  38908. }
  38909. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38910. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38911. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38912. serializationObject.uv2s._updatable = true;
  38913. }
  38914. }
  38915. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38916. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38917. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38918. serializationObject.uv3s._updatable = true;
  38919. }
  38920. }
  38921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38922. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38923. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38924. serializationObject.uv4s._updatable = true;
  38925. }
  38926. }
  38927. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38928. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38929. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38930. serializationObject.uv5s._updatable = true;
  38931. }
  38932. }
  38933. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38934. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38935. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38936. serializationObject.uv6s._updatable = true;
  38937. }
  38938. }
  38939. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38940. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38941. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38942. serializationObject.colors._updatable = true;
  38943. }
  38944. }
  38945. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38946. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38947. serializationObject.matricesIndices._isExpanded = true;
  38948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38949. serializationObject.matricesIndices._updatable = true;
  38950. }
  38951. }
  38952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38953. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38954. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38955. serializationObject.matricesWeights._updatable = true;
  38956. }
  38957. }
  38958. serializationObject.indices = this.toNumberArray(this.getIndices());
  38959. return serializationObject;
  38960. };
  38961. // Statics
  38962. /**
  38963. * Extracts a clone of a mesh geometry
  38964. * @param mesh defines the source mesh
  38965. * @param id defines the unique ID of the new geometry object
  38966. * @returns the new geometry object
  38967. */
  38968. Geometry.ExtractFromMesh = function (mesh, id) {
  38969. var geometry = mesh._geometry;
  38970. if (!geometry) {
  38971. return null;
  38972. }
  38973. return geometry.copy(id);
  38974. };
  38975. /**
  38976. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38977. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38978. * Be aware Math.random() could cause collisions, but:
  38979. * "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"
  38980. * @returns a string containing a new GUID
  38981. */
  38982. Geometry.RandomId = function () {
  38983. return BABYLON.Tools.RandomId();
  38984. };
  38985. /** @ignore */
  38986. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38987. var scene = mesh.getScene();
  38988. // Geometry
  38989. var geometryId = parsedGeometry.geometryId;
  38990. if (geometryId) {
  38991. var geometry = scene.getGeometryByID(geometryId);
  38992. if (geometry) {
  38993. geometry.applyToMesh(mesh);
  38994. }
  38995. }
  38996. else if (parsedGeometry instanceof ArrayBuffer) {
  38997. var binaryInfo = mesh._binaryInfo;
  38998. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38999. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39000. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39001. }
  39002. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39003. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39004. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39005. }
  39006. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39007. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39008. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39009. }
  39010. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39011. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39012. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39013. }
  39014. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39015. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39016. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39017. }
  39018. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39019. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39020. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39021. }
  39022. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39023. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39024. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39025. }
  39026. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39027. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39028. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39029. }
  39030. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39031. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39032. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39033. }
  39034. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39035. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39036. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39037. }
  39038. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39039. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39040. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39041. }
  39042. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39043. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39045. }
  39046. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39047. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39048. mesh.setIndices(indicesData, null);
  39049. }
  39050. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39051. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39052. mesh.subMeshes = [];
  39053. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39054. var materialIndex = subMeshesData[(i * 5) + 0];
  39055. var verticesStart = subMeshesData[(i * 5) + 1];
  39056. var verticesCount = subMeshesData[(i * 5) + 2];
  39057. var indexStart = subMeshesData[(i * 5) + 3];
  39058. var indexCount = subMeshesData[(i * 5) + 4];
  39059. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39060. }
  39061. }
  39062. }
  39063. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39064. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39065. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39066. if (parsedGeometry.tangents) {
  39067. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39068. }
  39069. if (parsedGeometry.uvs) {
  39070. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39071. }
  39072. if (parsedGeometry.uvs2) {
  39073. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39074. }
  39075. if (parsedGeometry.uvs3) {
  39076. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39077. }
  39078. if (parsedGeometry.uvs4) {
  39079. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39080. }
  39081. if (parsedGeometry.uvs5) {
  39082. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39083. }
  39084. if (parsedGeometry.uvs6) {
  39085. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39086. }
  39087. if (parsedGeometry.colors) {
  39088. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39089. }
  39090. if (parsedGeometry.matricesIndices) {
  39091. if (!parsedGeometry.matricesIndices._isExpanded) {
  39092. var floatIndices = [];
  39093. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39094. var matricesIndex = parsedGeometry.matricesIndices[i];
  39095. floatIndices.push(matricesIndex & 0x000000FF);
  39096. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39097. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39098. floatIndices.push(matricesIndex >> 24);
  39099. }
  39100. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39101. }
  39102. else {
  39103. delete parsedGeometry.matricesIndices._isExpanded;
  39104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39105. }
  39106. }
  39107. if (parsedGeometry.matricesIndicesExtra) {
  39108. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39109. var floatIndices = [];
  39110. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39111. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39112. floatIndices.push(matricesIndex & 0x000000FF);
  39113. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39114. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39115. floatIndices.push(matricesIndex >> 24);
  39116. }
  39117. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39118. }
  39119. else {
  39120. delete parsedGeometry.matricesIndices._isExpanded;
  39121. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39122. }
  39123. }
  39124. if (parsedGeometry.matricesWeights) {
  39125. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39126. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39127. }
  39128. if (parsedGeometry.matricesWeightsExtra) {
  39129. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39130. }
  39131. mesh.setIndices(parsedGeometry.indices, null);
  39132. }
  39133. // SubMeshes
  39134. if (parsedGeometry.subMeshes) {
  39135. mesh.subMeshes = [];
  39136. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39137. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39138. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39139. }
  39140. }
  39141. // Flat shading
  39142. if (mesh._shouldGenerateFlatShading) {
  39143. mesh.convertToFlatShadedMesh();
  39144. delete mesh._shouldGenerateFlatShading;
  39145. }
  39146. // Update
  39147. mesh.computeWorldMatrix(true);
  39148. // Octree
  39149. var sceneOctree = scene.selectionOctree;
  39150. if (sceneOctree !== undefined && sceneOctree !== null) {
  39151. sceneOctree.addMesh(mesh);
  39152. }
  39153. };
  39154. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39155. var epsilon = 1e-3;
  39156. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39157. return;
  39158. }
  39159. var noInfluenceBoneIndex = 0.0;
  39160. if (parsedGeometry.skeletonId > -1) {
  39161. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39162. if (!skeleton) {
  39163. return;
  39164. }
  39165. noInfluenceBoneIndex = skeleton.bones.length;
  39166. }
  39167. else {
  39168. return;
  39169. }
  39170. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39171. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39172. var matricesWeights = parsedGeometry.matricesWeights;
  39173. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39174. var influencers = parsedGeometry.numBoneInfluencer;
  39175. var size = matricesWeights.length;
  39176. for (var i = 0; i < size; i += 4) {
  39177. var weight = 0.0;
  39178. var firstZeroWeight = -1;
  39179. for (var j = 0; j < 4; j++) {
  39180. var w = matricesWeights[i + j];
  39181. weight += w;
  39182. if (w < epsilon && firstZeroWeight < 0) {
  39183. firstZeroWeight = j;
  39184. }
  39185. }
  39186. if (matricesWeightsExtra) {
  39187. for (var j = 0; j < 4; j++) {
  39188. var w = matricesWeightsExtra[i + j];
  39189. weight += w;
  39190. if (w < epsilon && firstZeroWeight < 0) {
  39191. firstZeroWeight = j + 4;
  39192. }
  39193. }
  39194. }
  39195. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39196. firstZeroWeight = influencers - 1;
  39197. }
  39198. if (weight > epsilon) {
  39199. var mweight = 1.0 / weight;
  39200. for (var j = 0; j < 4; j++) {
  39201. matricesWeights[i + j] *= mweight;
  39202. }
  39203. if (matricesWeightsExtra) {
  39204. for (var j = 0; j < 4; j++) {
  39205. matricesWeightsExtra[i + j] *= mweight;
  39206. }
  39207. }
  39208. }
  39209. else {
  39210. if (firstZeroWeight >= 4) {
  39211. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39212. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39213. }
  39214. else {
  39215. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39216. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39217. }
  39218. }
  39219. }
  39220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39221. if (parsedGeometry.matricesWeightsExtra) {
  39222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39223. }
  39224. };
  39225. /**
  39226. * Create a new geometry from persisted data (Using .babylon file format)
  39227. * @param parsedVertexData defines the persisted data
  39228. * @param scene defines the hosting scene
  39229. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39230. * @returns the new geometry object
  39231. */
  39232. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39233. if (scene.getGeometryByID(parsedVertexData.id)) {
  39234. return null; // null since geometry could be something else than a box...
  39235. }
  39236. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39237. if (BABYLON.Tags) {
  39238. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39239. }
  39240. if (parsedVertexData.delayLoadingFile) {
  39241. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39242. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39243. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39244. geometry._delayInfo = [];
  39245. if (parsedVertexData.hasUVs) {
  39246. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39247. }
  39248. if (parsedVertexData.hasUVs2) {
  39249. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39250. }
  39251. if (parsedVertexData.hasUVs3) {
  39252. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39253. }
  39254. if (parsedVertexData.hasUVs4) {
  39255. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39256. }
  39257. if (parsedVertexData.hasUVs5) {
  39258. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39259. }
  39260. if (parsedVertexData.hasUVs6) {
  39261. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39262. }
  39263. if (parsedVertexData.hasColors) {
  39264. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39265. }
  39266. if (parsedVertexData.hasMatricesIndices) {
  39267. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39268. }
  39269. if (parsedVertexData.hasMatricesWeights) {
  39270. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39271. }
  39272. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39273. }
  39274. else {
  39275. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39276. }
  39277. scene.pushGeometry(geometry, true);
  39278. return geometry;
  39279. };
  39280. return Geometry;
  39281. }());
  39282. BABYLON.Geometry = Geometry;
  39283. // Primitives
  39284. /// Abstract class
  39285. /**
  39286. * Abstract class used to provide common services for all typed geometries
  39287. */
  39288. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39289. __extends(_PrimitiveGeometry, _super);
  39290. /**
  39291. * Creates a new typed geometry
  39292. * @param id defines the unique ID of the geometry
  39293. * @param scene defines the hosting scene
  39294. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39295. * @param mesh defines the hosting mesh (can be null)
  39296. */
  39297. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39298. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39299. if (mesh === void 0) { mesh = null; }
  39300. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39301. _this._canBeRegenerated = _canBeRegenerated;
  39302. _this._beingRegenerated = true;
  39303. _this.regenerate();
  39304. _this._beingRegenerated = false;
  39305. return _this;
  39306. }
  39307. /**
  39308. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39309. * @returns true if the geometry can be regenerated
  39310. */
  39311. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39312. return this._canBeRegenerated;
  39313. };
  39314. /**
  39315. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39316. */
  39317. _PrimitiveGeometry.prototype.regenerate = function () {
  39318. if (!this._canBeRegenerated) {
  39319. return;
  39320. }
  39321. this._beingRegenerated = true;
  39322. this.setAllVerticesData(this._regenerateVertexData(), false);
  39323. this._beingRegenerated = false;
  39324. };
  39325. /**
  39326. * Clone the geometry
  39327. * @param id defines the unique ID of the new geometry
  39328. * @returns the new geometry
  39329. */
  39330. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39331. return _super.prototype.copy.call(this, id);
  39332. };
  39333. // overrides
  39334. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39335. if (!this._beingRegenerated) {
  39336. return;
  39337. }
  39338. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39339. };
  39340. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39341. if (!this._beingRegenerated) {
  39342. return;
  39343. }
  39344. _super.prototype.setVerticesData.call(this, kind, data, false);
  39345. };
  39346. // to override
  39347. /** @ignore */
  39348. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39349. throw new Error("Abstract method");
  39350. };
  39351. _PrimitiveGeometry.prototype.copy = function (id) {
  39352. throw new Error("Must be overriden in sub-classes.");
  39353. };
  39354. _PrimitiveGeometry.prototype.serialize = function () {
  39355. var serializationObject = _super.prototype.serialize.call(this);
  39356. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39357. return serializationObject;
  39358. };
  39359. return _PrimitiveGeometry;
  39360. }(Geometry));
  39361. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39362. /**
  39363. * Creates a ribbon geometry
  39364. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39365. */
  39366. var RibbonGeometry = /** @class */ (function (_super) {
  39367. __extends(RibbonGeometry, _super);
  39368. /**
  39369. * Creates a ribbon geometry
  39370. * @param id defines the unique ID of the geometry
  39371. * @param scene defines the hosting scene
  39372. * @param pathArray defines the array of paths to use
  39373. * @param closeArray defines if the last path and the first path must be joined
  39374. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39375. * @param offset defines the offset between points
  39376. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39377. * @param mesh defines the hosting mesh (can be null)
  39378. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39379. */
  39380. function RibbonGeometry(id, scene,
  39381. /**
  39382. * Defines the array of paths to use
  39383. */
  39384. pathArray,
  39385. /**
  39386. * Defines if the last and first points of each path in your pathArray must be joined
  39387. */
  39388. closeArray,
  39389. /**
  39390. * Defines if the last and first points of each path in your pathArray must be joined
  39391. */
  39392. closePath,
  39393. /**
  39394. * Defines the offset between points
  39395. */
  39396. offset, canBeRegenerated, mesh,
  39397. /**
  39398. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39399. */
  39400. side) {
  39401. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39402. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39403. _this.pathArray = pathArray;
  39404. _this.closeArray = closeArray;
  39405. _this.closePath = closePath;
  39406. _this.offset = offset;
  39407. _this.side = side;
  39408. return _this;
  39409. }
  39410. /** @ignore */
  39411. RibbonGeometry.prototype._regenerateVertexData = function () {
  39412. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39413. };
  39414. RibbonGeometry.prototype.copy = function (id) {
  39415. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39416. };
  39417. return RibbonGeometry;
  39418. }(_PrimitiveGeometry));
  39419. BABYLON.RibbonGeometry = RibbonGeometry;
  39420. /**
  39421. * Creates a box geometry
  39422. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39423. */
  39424. var BoxGeometry = /** @class */ (function (_super) {
  39425. __extends(BoxGeometry, _super);
  39426. /**
  39427. * Creates a box geometry
  39428. * @param id defines the unique ID of the geometry
  39429. * @param scene defines the hosting scene
  39430. * @param size defines the zise of the box (width, height and depth are the same)
  39431. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39432. * @param mesh defines the hosting mesh (can be null)
  39433. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39434. */
  39435. function BoxGeometry(id, scene,
  39436. /**
  39437. * Defines the zise of the box (width, height and depth are the same)
  39438. */
  39439. size, canBeRegenerated, mesh,
  39440. /**
  39441. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39442. */
  39443. side) {
  39444. if (mesh === void 0) { mesh = null; }
  39445. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39446. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39447. _this.size = size;
  39448. _this.side = side;
  39449. return _this;
  39450. }
  39451. BoxGeometry.prototype._regenerateVertexData = function () {
  39452. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39453. };
  39454. BoxGeometry.prototype.copy = function (id) {
  39455. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39456. };
  39457. BoxGeometry.prototype.serialize = function () {
  39458. var serializationObject = _super.prototype.serialize.call(this);
  39459. serializationObject.size = this.size;
  39460. return serializationObject;
  39461. };
  39462. BoxGeometry.Parse = function (parsedBox, scene) {
  39463. if (scene.getGeometryByID(parsedBox.id)) {
  39464. return null; // null since geometry could be something else than a box...
  39465. }
  39466. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39467. if (BABYLON.Tags) {
  39468. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39469. }
  39470. scene.pushGeometry(box, true);
  39471. return box;
  39472. };
  39473. return BoxGeometry;
  39474. }(_PrimitiveGeometry));
  39475. BABYLON.BoxGeometry = BoxGeometry;
  39476. /**
  39477. * Creates a sphere geometry
  39478. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39479. */
  39480. var SphereGeometry = /** @class */ (function (_super) {
  39481. __extends(SphereGeometry, _super);
  39482. /**
  39483. * Create a new sphere geometry
  39484. * @param id defines the unique ID of the geometry
  39485. * @param scene defines the hosting scene
  39486. * @param segments defines the number of segments to use to create the sphere
  39487. * @param diameter defines the diameter of the sphere
  39488. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39489. * @param mesh defines the hosting mesh (can be null)
  39490. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39491. */
  39492. function SphereGeometry(id, scene,
  39493. /**
  39494. * Defines the number of segments to use to create the sphere
  39495. */
  39496. segments,
  39497. /**
  39498. * Defines the diameter of the sphere
  39499. */
  39500. diameter, canBeRegenerated, mesh,
  39501. /**
  39502. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39503. */
  39504. side) {
  39505. if (mesh === void 0) { mesh = null; }
  39506. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39507. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39508. _this.segments = segments;
  39509. _this.diameter = diameter;
  39510. _this.side = side;
  39511. return _this;
  39512. }
  39513. SphereGeometry.prototype._regenerateVertexData = function () {
  39514. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39515. };
  39516. SphereGeometry.prototype.copy = function (id) {
  39517. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39518. };
  39519. SphereGeometry.prototype.serialize = function () {
  39520. var serializationObject = _super.prototype.serialize.call(this);
  39521. serializationObject.segments = this.segments;
  39522. serializationObject.diameter = this.diameter;
  39523. return serializationObject;
  39524. };
  39525. SphereGeometry.Parse = function (parsedSphere, scene) {
  39526. if (scene.getGeometryByID(parsedSphere.id)) {
  39527. return null; // null since geometry could be something else than a sphere...
  39528. }
  39529. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39530. if (BABYLON.Tags) {
  39531. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39532. }
  39533. scene.pushGeometry(sphere, true);
  39534. return sphere;
  39535. };
  39536. return SphereGeometry;
  39537. }(_PrimitiveGeometry));
  39538. BABYLON.SphereGeometry = SphereGeometry;
  39539. /**
  39540. * Creates a disc geometry
  39541. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39542. */
  39543. var DiscGeometry = /** @class */ (function (_super) {
  39544. __extends(DiscGeometry, _super);
  39545. /**
  39546. * Creates a new disc geometry
  39547. * @param id defines the unique ID of the geometry
  39548. * @param scene defines the hosting scene
  39549. * @param radius defines the radius of the disc
  39550. * @param tessellation defines the tesselation factor to apply to the disc
  39551. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39552. * @param mesh defines the hosting mesh (can be null)
  39553. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39554. */
  39555. function DiscGeometry(id, scene,
  39556. /**
  39557. * Defines the radius of the disc
  39558. */
  39559. radius,
  39560. /**
  39561. * Defines the tesselation factor to apply to the disc
  39562. */
  39563. tessellation, canBeRegenerated, mesh,
  39564. /**
  39565. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39566. */
  39567. side) {
  39568. if (mesh === void 0) { mesh = null; }
  39569. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39570. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39571. _this.radius = radius;
  39572. _this.tessellation = tessellation;
  39573. _this.side = side;
  39574. return _this;
  39575. }
  39576. DiscGeometry.prototype._regenerateVertexData = function () {
  39577. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39578. };
  39579. DiscGeometry.prototype.copy = function (id) {
  39580. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39581. };
  39582. return DiscGeometry;
  39583. }(_PrimitiveGeometry));
  39584. BABYLON.DiscGeometry = DiscGeometry;
  39585. /**
  39586. * Creates a new cylinder geometry
  39587. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39588. */
  39589. var CylinderGeometry = /** @class */ (function (_super) {
  39590. __extends(CylinderGeometry, _super);
  39591. /**
  39592. * Creates a new cylinder geometry
  39593. * @param id defines the unique ID of the geometry
  39594. * @param scene defines the hosting scene
  39595. * @param height defines the height of the cylinder
  39596. * @param diameterTop defines the diameter of the cylinder's top cap
  39597. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39598. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39599. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39600. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39601. * @param mesh defines the hosting mesh (can be null)
  39602. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39603. */
  39604. function CylinderGeometry(id, scene,
  39605. /**
  39606. * Defines the height of the cylinder
  39607. */
  39608. height,
  39609. /**
  39610. * Defines the diameter of the cylinder's top cap
  39611. */
  39612. diameterTop,
  39613. /**
  39614. * Defines the diameter of the cylinder's bottom cap
  39615. */
  39616. diameterBottom,
  39617. /**
  39618. * Defines the tessellation factor to apply to the cylinder
  39619. */
  39620. tessellation,
  39621. /**
  39622. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39623. */
  39624. subdivisions, canBeRegenerated, mesh,
  39625. /**
  39626. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39627. */
  39628. side) {
  39629. if (subdivisions === void 0) { subdivisions = 1; }
  39630. if (mesh === void 0) { mesh = null; }
  39631. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39632. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39633. _this.height = height;
  39634. _this.diameterTop = diameterTop;
  39635. _this.diameterBottom = diameterBottom;
  39636. _this.tessellation = tessellation;
  39637. _this.subdivisions = subdivisions;
  39638. _this.side = side;
  39639. return _this;
  39640. }
  39641. CylinderGeometry.prototype._regenerateVertexData = function () {
  39642. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39643. };
  39644. CylinderGeometry.prototype.copy = function (id) {
  39645. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39646. };
  39647. CylinderGeometry.prototype.serialize = function () {
  39648. var serializationObject = _super.prototype.serialize.call(this);
  39649. serializationObject.height = this.height;
  39650. serializationObject.diameterTop = this.diameterTop;
  39651. serializationObject.diameterBottom = this.diameterBottom;
  39652. serializationObject.tessellation = this.tessellation;
  39653. return serializationObject;
  39654. };
  39655. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39656. if (scene.getGeometryByID(parsedCylinder.id)) {
  39657. return null; // null since geometry could be something else than a cylinder...
  39658. }
  39659. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39660. if (BABYLON.Tags) {
  39661. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39662. }
  39663. scene.pushGeometry(cylinder, true);
  39664. return cylinder;
  39665. };
  39666. return CylinderGeometry;
  39667. }(_PrimitiveGeometry));
  39668. BABYLON.CylinderGeometry = CylinderGeometry;
  39669. /**
  39670. * Creates a new torus geometry
  39671. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39672. */
  39673. var TorusGeometry = /** @class */ (function (_super) {
  39674. __extends(TorusGeometry, _super);
  39675. /**
  39676. * Creates a new torus geometry
  39677. * @param id defines the unique ID of the geometry
  39678. * @param scene defines the hosting scene
  39679. * @param diameter defines the diameter of the torus
  39680. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39681. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39682. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39683. * @param mesh defines the hosting mesh (can be null)
  39684. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39685. */
  39686. function TorusGeometry(id, scene,
  39687. /**
  39688. * Defines the diameter of the torus
  39689. */
  39690. diameter,
  39691. /**
  39692. * Defines the thickness of the torus (ie. internal diameter)
  39693. */
  39694. thickness,
  39695. /**
  39696. * Defines the tesselation factor to apply to the torus
  39697. */
  39698. tessellation, canBeRegenerated, mesh,
  39699. /**
  39700. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39701. */
  39702. side) {
  39703. if (mesh === void 0) { mesh = null; }
  39704. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39705. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39706. _this.diameter = diameter;
  39707. _this.thickness = thickness;
  39708. _this.tessellation = tessellation;
  39709. _this.side = side;
  39710. return _this;
  39711. }
  39712. TorusGeometry.prototype._regenerateVertexData = function () {
  39713. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39714. };
  39715. TorusGeometry.prototype.copy = function (id) {
  39716. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39717. };
  39718. TorusGeometry.prototype.serialize = function () {
  39719. var serializationObject = _super.prototype.serialize.call(this);
  39720. serializationObject.diameter = this.diameter;
  39721. serializationObject.thickness = this.thickness;
  39722. serializationObject.tessellation = this.tessellation;
  39723. return serializationObject;
  39724. };
  39725. TorusGeometry.Parse = function (parsedTorus, scene) {
  39726. if (scene.getGeometryByID(parsedTorus.id)) {
  39727. return null; // null since geometry could be something else than a torus...
  39728. }
  39729. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39730. if (BABYLON.Tags) {
  39731. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39732. }
  39733. scene.pushGeometry(torus, true);
  39734. return torus;
  39735. };
  39736. return TorusGeometry;
  39737. }(_PrimitiveGeometry));
  39738. BABYLON.TorusGeometry = TorusGeometry;
  39739. /**
  39740. * Creates a new ground geometry
  39741. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39742. */
  39743. var GroundGeometry = /** @class */ (function (_super) {
  39744. __extends(GroundGeometry, _super);
  39745. /**
  39746. * Creates a new ground geometry
  39747. * @param id defines the unique ID of the geometry
  39748. * @param scene defines the hosting scene
  39749. * @param width defines the width of the ground
  39750. * @param height defines the height of the ground
  39751. * @param subdivisions defines the subdivisions to apply to the ground
  39752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39753. * @param mesh defines the hosting mesh (can be null)
  39754. */
  39755. function GroundGeometry(id, scene,
  39756. /**
  39757. * Defines the width of the ground
  39758. */
  39759. width,
  39760. /**
  39761. * Defines the height of the ground
  39762. */
  39763. height,
  39764. /**
  39765. * Defines the subdivisions to apply to the ground
  39766. */
  39767. subdivisions, canBeRegenerated, mesh) {
  39768. if (mesh === void 0) { mesh = null; }
  39769. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39770. _this.width = width;
  39771. _this.height = height;
  39772. _this.subdivisions = subdivisions;
  39773. return _this;
  39774. }
  39775. GroundGeometry.prototype._regenerateVertexData = function () {
  39776. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39777. };
  39778. GroundGeometry.prototype.copy = function (id) {
  39779. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39780. };
  39781. GroundGeometry.prototype.serialize = function () {
  39782. var serializationObject = _super.prototype.serialize.call(this);
  39783. serializationObject.width = this.width;
  39784. serializationObject.height = this.height;
  39785. serializationObject.subdivisions = this.subdivisions;
  39786. return serializationObject;
  39787. };
  39788. GroundGeometry.Parse = function (parsedGround, scene) {
  39789. if (scene.getGeometryByID(parsedGround.id)) {
  39790. return null; // null since geometry could be something else than a ground...
  39791. }
  39792. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39793. if (BABYLON.Tags) {
  39794. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39795. }
  39796. scene.pushGeometry(ground, true);
  39797. return ground;
  39798. };
  39799. return GroundGeometry;
  39800. }(_PrimitiveGeometry));
  39801. BABYLON.GroundGeometry = GroundGeometry;
  39802. /**
  39803. * Creates a tiled ground geometry
  39804. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39805. */
  39806. var TiledGroundGeometry = /** @class */ (function (_super) {
  39807. __extends(TiledGroundGeometry, _super);
  39808. /**
  39809. * Creates a tiled ground geometry
  39810. * @param id defines the unique ID of the geometry
  39811. * @param scene defines the hosting scene
  39812. * @param xmin defines the minimum value on X axis
  39813. * @param zmin defines the minimum value on Z axis
  39814. * @param xmax defines the maximum value on X axis
  39815. * @param zmax defines the maximum value on Z axis
  39816. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39817. * @param precision defines the precision to use when computing the tiles
  39818. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39819. * @param mesh defines the hosting mesh (can be null)
  39820. */
  39821. function TiledGroundGeometry(id, scene,
  39822. /**
  39823. * Defines the minimum value on X axis
  39824. */
  39825. xmin,
  39826. /**
  39827. * Defines the minimum value on Z axis
  39828. */
  39829. zmin,
  39830. /**
  39831. * Defines the maximum value on X axis
  39832. */
  39833. xmax,
  39834. /**
  39835. * Defines the maximum value on Z axis
  39836. */
  39837. zmax,
  39838. /**
  39839. * Defines the subdivisions to apply to the ground
  39840. */
  39841. subdivisions,
  39842. /**
  39843. * Defines the precision to use when computing the tiles
  39844. */
  39845. precision, canBeRegenerated, mesh) {
  39846. if (mesh === void 0) { mesh = null; }
  39847. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39848. _this.xmin = xmin;
  39849. _this.zmin = zmin;
  39850. _this.xmax = xmax;
  39851. _this.zmax = zmax;
  39852. _this.subdivisions = subdivisions;
  39853. _this.precision = precision;
  39854. return _this;
  39855. }
  39856. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39857. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39858. };
  39859. TiledGroundGeometry.prototype.copy = function (id) {
  39860. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39861. };
  39862. return TiledGroundGeometry;
  39863. }(_PrimitiveGeometry));
  39864. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39865. /**
  39866. * Creates a plane geometry
  39867. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39868. */
  39869. var PlaneGeometry = /** @class */ (function (_super) {
  39870. __extends(PlaneGeometry, _super);
  39871. /**
  39872. * Creates a plane geometry
  39873. * @param id defines the unique ID of the geometry
  39874. * @param scene defines the hosting scene
  39875. * @param size defines the size of the plane (width === height)
  39876. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39877. * @param mesh defines the hosting mesh (can be null)
  39878. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39879. */
  39880. function PlaneGeometry(id, scene,
  39881. /**
  39882. * Defines the size of the plane (width === height)
  39883. */
  39884. size, canBeRegenerated, mesh,
  39885. /**
  39886. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39887. */
  39888. side) {
  39889. if (mesh === void 0) { mesh = null; }
  39890. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39892. _this.size = size;
  39893. _this.side = side;
  39894. return _this;
  39895. }
  39896. PlaneGeometry.prototype._regenerateVertexData = function () {
  39897. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39898. };
  39899. PlaneGeometry.prototype.copy = function (id) {
  39900. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39901. };
  39902. PlaneGeometry.prototype.serialize = function () {
  39903. var serializationObject = _super.prototype.serialize.call(this);
  39904. serializationObject.size = this.size;
  39905. return serializationObject;
  39906. };
  39907. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39908. if (scene.getGeometryByID(parsedPlane.id)) {
  39909. return null; // null since geometry could be something else than a ground...
  39910. }
  39911. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39912. if (BABYLON.Tags) {
  39913. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39914. }
  39915. scene.pushGeometry(plane, true);
  39916. return plane;
  39917. };
  39918. return PlaneGeometry;
  39919. }(_PrimitiveGeometry));
  39920. BABYLON.PlaneGeometry = PlaneGeometry;
  39921. /**
  39922. * Creates a torus knot geometry
  39923. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39924. */
  39925. var TorusKnotGeometry = /** @class */ (function (_super) {
  39926. __extends(TorusKnotGeometry, _super);
  39927. /**
  39928. * Creates a torus knot geometry
  39929. * @param id defines the unique ID of the geometry
  39930. * @param scene defines the hosting scene
  39931. * @param radius defines the radius of the torus knot
  39932. * @param tube defines the thickness of the torus knot tube
  39933. * @param radialSegments defines the number of radial segments
  39934. * @param tubularSegments defines the number of tubular segments
  39935. * @param p defines the first number of windings
  39936. * @param q defines the second number of windings
  39937. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39938. * @param mesh defines the hosting mesh (can be null)
  39939. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39940. */
  39941. function TorusKnotGeometry(id, scene,
  39942. /**
  39943. * Defines the radius of the torus knot
  39944. */
  39945. radius,
  39946. /**
  39947. * Defines the thickness of the torus knot tube
  39948. */
  39949. tube,
  39950. /**
  39951. * Defines the number of radial segments
  39952. */
  39953. radialSegments,
  39954. /**
  39955. * Defines the number of tubular segments
  39956. */
  39957. tubularSegments,
  39958. /**
  39959. * Defines the first number of windings
  39960. */
  39961. p,
  39962. /**
  39963. * Defines the second number of windings
  39964. */
  39965. q, canBeRegenerated, mesh,
  39966. /**
  39967. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39968. */
  39969. side) {
  39970. if (mesh === void 0) { mesh = null; }
  39971. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39972. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39973. _this.radius = radius;
  39974. _this.tube = tube;
  39975. _this.radialSegments = radialSegments;
  39976. _this.tubularSegments = tubularSegments;
  39977. _this.p = p;
  39978. _this.q = q;
  39979. _this.side = side;
  39980. return _this;
  39981. }
  39982. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39983. 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 });
  39984. };
  39985. TorusKnotGeometry.prototype.copy = function (id) {
  39986. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39987. };
  39988. TorusKnotGeometry.prototype.serialize = function () {
  39989. var serializationObject = _super.prototype.serialize.call(this);
  39990. serializationObject.radius = this.radius;
  39991. serializationObject.tube = this.tube;
  39992. serializationObject.radialSegments = this.radialSegments;
  39993. serializationObject.tubularSegments = this.tubularSegments;
  39994. serializationObject.p = this.p;
  39995. serializationObject.q = this.q;
  39996. return serializationObject;
  39997. };
  39998. ;
  39999. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40000. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40001. return null; // null since geometry could be something else than a ground...
  40002. }
  40003. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40004. if (BABYLON.Tags) {
  40005. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40006. }
  40007. scene.pushGeometry(torusKnot, true);
  40008. return torusKnot;
  40009. };
  40010. return TorusKnotGeometry;
  40011. }(_PrimitiveGeometry));
  40012. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40013. //}
  40014. })(BABYLON || (BABYLON = {}));
  40015. //# sourceMappingURL=babylon.geometry.js.map
  40016. var BABYLON;
  40017. (function (BABYLON) {
  40018. /**
  40019. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40020. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40021. */
  40022. var PostProcessManager = /** @class */ (function () {
  40023. /**
  40024. * Creates a new instance PostProcess
  40025. * @param scene The scene that the post process is associated with.
  40026. */
  40027. function PostProcessManager(scene) {
  40028. this._vertexBuffers = {};
  40029. this._scene = scene;
  40030. }
  40031. PostProcessManager.prototype._prepareBuffers = function () {
  40032. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40033. return;
  40034. }
  40035. // VBO
  40036. var vertices = [];
  40037. vertices.push(1, 1);
  40038. vertices.push(-1, 1);
  40039. vertices.push(-1, -1);
  40040. vertices.push(1, -1);
  40041. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40042. this._buildIndexBuffer();
  40043. };
  40044. PostProcessManager.prototype._buildIndexBuffer = function () {
  40045. // Indices
  40046. var indices = [];
  40047. indices.push(0);
  40048. indices.push(1);
  40049. indices.push(2);
  40050. indices.push(0);
  40051. indices.push(2);
  40052. indices.push(3);
  40053. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40054. };
  40055. /**
  40056. * Rebuilds the vertex buffers of the manager.
  40057. */
  40058. PostProcessManager.prototype._rebuild = function () {
  40059. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40060. if (!vb) {
  40061. return;
  40062. }
  40063. vb._rebuild();
  40064. this._buildIndexBuffer();
  40065. };
  40066. // Methods
  40067. /**
  40068. * Prepares a frame to be run through a post process.
  40069. * @param sourceTexture The input texture to the post procesess. (default: null)
  40070. * @param postProcesses An array of post processes to be run. (default: null)
  40071. * @returns True if the post processes were able to be run.
  40072. */
  40073. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40074. if (sourceTexture === void 0) { sourceTexture = null; }
  40075. if (postProcesses === void 0) { postProcesses = null; }
  40076. var camera = this._scene.activeCamera;
  40077. if (!camera) {
  40078. return false;
  40079. }
  40080. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40081. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40082. return false;
  40083. }
  40084. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40085. return true;
  40086. };
  40087. /**
  40088. * Manually render a set of post processes to a texture.
  40089. * @param postProcesses An array of post processes to be run.
  40090. * @param targetTexture The target texture to render to.
  40091. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40092. */
  40093. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40094. if (targetTexture === void 0) { targetTexture = null; }
  40095. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40096. var engine = this._scene.getEngine();
  40097. for (var index = 0; index < postProcesses.length; index++) {
  40098. if (index < postProcesses.length - 1) {
  40099. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40100. }
  40101. else {
  40102. if (targetTexture) {
  40103. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40104. }
  40105. else {
  40106. engine.restoreDefaultFramebuffer();
  40107. }
  40108. }
  40109. var pp = postProcesses[index];
  40110. var effect = pp.apply();
  40111. if (effect) {
  40112. pp.onBeforeRenderObservable.notifyObservers(effect);
  40113. // VBOs
  40114. this._prepareBuffers();
  40115. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40116. // Draw order
  40117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40118. pp.onAfterRenderObservable.notifyObservers(effect);
  40119. }
  40120. }
  40121. // Restore depth buffer
  40122. engine.setDepthBuffer(true);
  40123. engine.setDepthWrite(true);
  40124. };
  40125. /**
  40126. * Finalize the result of the output of the postprocesses.
  40127. * @param doNotPresent If true the result will not be displayed to the screen.
  40128. * @param targetTexture The target texture to render to.
  40129. * @param faceIndex The index of the face to bind the target texture to.
  40130. * @param postProcesses The array of post processes to render.
  40131. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40132. */
  40133. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40134. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40135. var camera = this._scene.activeCamera;
  40136. if (!camera) {
  40137. return;
  40138. }
  40139. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40140. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40141. return;
  40142. }
  40143. var engine = this._scene.getEngine();
  40144. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40145. var pp = postProcesses[index];
  40146. if (index < len - 1) {
  40147. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40148. }
  40149. else {
  40150. if (targetTexture) {
  40151. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40152. pp._outputTexture = targetTexture;
  40153. }
  40154. else {
  40155. engine.restoreDefaultFramebuffer();
  40156. pp._outputTexture = null;
  40157. }
  40158. }
  40159. if (doNotPresent) {
  40160. break;
  40161. }
  40162. var effect = pp.apply();
  40163. if (effect) {
  40164. pp.onBeforeRenderObservable.notifyObservers(effect);
  40165. // VBOs
  40166. this._prepareBuffers();
  40167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40168. // Draw order
  40169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40170. pp.onAfterRenderObservable.notifyObservers(effect);
  40171. }
  40172. }
  40173. // Restore states
  40174. engine.setDepthBuffer(true);
  40175. engine.setDepthWrite(true);
  40176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40177. };
  40178. /**
  40179. * Disposes of the post process manager.
  40180. */
  40181. PostProcessManager.prototype.dispose = function () {
  40182. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40183. if (buffer) {
  40184. buffer.dispose();
  40185. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40186. }
  40187. if (this._indexBuffer) {
  40188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40189. this._indexBuffer = null;
  40190. }
  40191. };
  40192. return PostProcessManager;
  40193. }());
  40194. BABYLON.PostProcessManager = PostProcessManager;
  40195. })(BABYLON || (BABYLON = {}));
  40196. //# sourceMappingURL=babylon.postProcessManager.js.map
  40197. var BABYLON;
  40198. (function (BABYLON) {
  40199. /**
  40200. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40201. */
  40202. var PerformanceMonitor = /** @class */ (function () {
  40203. /**
  40204. * constructor
  40205. * @param frameSampleSize The number of samples required to saturate the sliding window
  40206. */
  40207. function PerformanceMonitor(frameSampleSize) {
  40208. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40209. this._enabled = true;
  40210. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40211. }
  40212. /**
  40213. * Samples current frame
  40214. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40215. */
  40216. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40217. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40218. if (!this._enabled)
  40219. return;
  40220. if (this._lastFrameTimeMs != null) {
  40221. var dt = timeMs - this._lastFrameTimeMs;
  40222. this._rollingFrameTime.add(dt);
  40223. }
  40224. this._lastFrameTimeMs = timeMs;
  40225. };
  40226. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40227. /**
  40228. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40229. * @return Average frame time in milliseconds
  40230. */
  40231. get: function () {
  40232. return this._rollingFrameTime.average;
  40233. },
  40234. enumerable: true,
  40235. configurable: true
  40236. });
  40237. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40238. /**
  40239. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40240. * @return Frame time variance in milliseconds squared
  40241. */
  40242. get: function () {
  40243. return this._rollingFrameTime.variance;
  40244. },
  40245. enumerable: true,
  40246. configurable: true
  40247. });
  40248. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40249. /**
  40250. * Returns the frame time of the most recent frame
  40251. * @return Frame time in milliseconds
  40252. */
  40253. get: function () {
  40254. return this._rollingFrameTime.history(0);
  40255. },
  40256. enumerable: true,
  40257. configurable: true
  40258. });
  40259. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40260. /**
  40261. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40262. * @return Framerate in frames per second
  40263. */
  40264. get: function () {
  40265. return 1000.0 / this._rollingFrameTime.average;
  40266. },
  40267. enumerable: true,
  40268. configurable: true
  40269. });
  40270. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40271. /**
  40272. * Returns the average framerate in frames per second using the most recent frame time
  40273. * @return Framerate in frames per second
  40274. */
  40275. get: function () {
  40276. var history = this._rollingFrameTime.history(0);
  40277. if (history === 0) {
  40278. return 0;
  40279. }
  40280. return 1000.0 / history;
  40281. },
  40282. enumerable: true,
  40283. configurable: true
  40284. });
  40285. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40286. /**
  40287. * Returns true if enough samples have been taken to completely fill the sliding window
  40288. * @return true if saturated
  40289. */
  40290. get: function () {
  40291. return this._rollingFrameTime.isSaturated();
  40292. },
  40293. enumerable: true,
  40294. configurable: true
  40295. });
  40296. /**
  40297. * Enables contributions to the sliding window sample set
  40298. */
  40299. PerformanceMonitor.prototype.enable = function () {
  40300. this._enabled = true;
  40301. };
  40302. /**
  40303. * Disables contributions to the sliding window sample set
  40304. * Samples will not be interpolated over the disabled period
  40305. */
  40306. PerformanceMonitor.prototype.disable = function () {
  40307. this._enabled = false;
  40308. //clear last sample to avoid interpolating over the disabled period when next enabled
  40309. this._lastFrameTimeMs = null;
  40310. };
  40311. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40312. /**
  40313. * Returns true if sampling is enabled
  40314. * @return true if enabled
  40315. */
  40316. get: function () {
  40317. return this._enabled;
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. /**
  40323. * Resets performance monitor
  40324. */
  40325. PerformanceMonitor.prototype.reset = function () {
  40326. //clear last sample to avoid interpolating over the disabled period when next enabled
  40327. this._lastFrameTimeMs = null;
  40328. //wipe record
  40329. this._rollingFrameTime.reset();
  40330. };
  40331. return PerformanceMonitor;
  40332. }());
  40333. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40334. /**
  40335. * RollingAverage
  40336. *
  40337. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40338. */
  40339. var RollingAverage = /** @class */ (function () {
  40340. /**
  40341. * constructor
  40342. * @param length The number of samples required to saturate the sliding window
  40343. */
  40344. function RollingAverage(length) {
  40345. this._samples = new Array(length);
  40346. this.reset();
  40347. }
  40348. /**
  40349. * Adds a sample to the sample set
  40350. * @param v The sample value
  40351. */
  40352. RollingAverage.prototype.add = function (v) {
  40353. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40354. var delta;
  40355. //we need to check if we've already wrapped round
  40356. if (this.isSaturated()) {
  40357. //remove bottom of stack from mean
  40358. var bottomValue = this._samples[this._pos];
  40359. delta = bottomValue - this.average;
  40360. this.average -= delta / (this._sampleCount - 1);
  40361. this._m2 -= delta * (bottomValue - this.average);
  40362. }
  40363. else {
  40364. this._sampleCount++;
  40365. }
  40366. //add new value to mean
  40367. delta = v - this.average;
  40368. this.average += delta / (this._sampleCount);
  40369. this._m2 += delta * (v - this.average);
  40370. //set the new variance
  40371. this.variance = this._m2 / (this._sampleCount - 1);
  40372. this._samples[this._pos] = v;
  40373. this._pos++;
  40374. this._pos %= this._samples.length; //positive wrap around
  40375. };
  40376. /**
  40377. * Returns previously added values or null if outside of history or outside the sliding window domain
  40378. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40379. * @return Value previously recorded with add() or null if outside of range
  40380. */
  40381. RollingAverage.prototype.history = function (i) {
  40382. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40383. return 0;
  40384. }
  40385. var i0 = this._wrapPosition(this._pos - 1.0);
  40386. return this._samples[this._wrapPosition(i0 - i)];
  40387. };
  40388. /**
  40389. * Returns true if enough samples have been taken to completely fill the sliding window
  40390. * @return true if sample-set saturated
  40391. */
  40392. RollingAverage.prototype.isSaturated = function () {
  40393. return this._sampleCount >= this._samples.length;
  40394. };
  40395. /**
  40396. * Resets the rolling average (equivalent to 0 samples taken so far)
  40397. */
  40398. RollingAverage.prototype.reset = function () {
  40399. this.average = 0;
  40400. this.variance = 0;
  40401. this._sampleCount = 0;
  40402. this._pos = 0;
  40403. this._m2 = 0;
  40404. };
  40405. /**
  40406. * Wraps a value around the sample range boundaries
  40407. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40408. * @return Wrapped position in sample range
  40409. */
  40410. RollingAverage.prototype._wrapPosition = function (i) {
  40411. var max = this._samples.length;
  40412. return ((i % max) + max) % max;
  40413. };
  40414. return RollingAverage;
  40415. }());
  40416. BABYLON.RollingAverage = RollingAverage;
  40417. })(BABYLON || (BABYLON = {}));
  40418. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40419. var BABYLON;
  40420. (function (BABYLON) {
  40421. /**
  40422. * This groups together the common properties used for image processing either in direct forward pass
  40423. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40424. * or not.
  40425. */
  40426. var ImageProcessingConfiguration = /** @class */ (function () {
  40427. function ImageProcessingConfiguration() {
  40428. /**
  40429. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40430. */
  40431. this.colorCurves = new BABYLON.ColorCurves();
  40432. this._colorCurvesEnabled = false;
  40433. this._colorGradingEnabled = false;
  40434. this._colorGradingWithGreenDepth = true;
  40435. this._colorGradingBGR = true;
  40436. this._exposure = 1.0;
  40437. this._toneMappingEnabled = false;
  40438. this._contrast = 1.0;
  40439. /**
  40440. * Vignette stretch size.
  40441. */
  40442. this.vignetteStretch = 0;
  40443. /**
  40444. * Vignette centre X Offset.
  40445. */
  40446. this.vignetteCentreX = 0;
  40447. /**
  40448. * Vignette centre Y Offset.
  40449. */
  40450. this.vignetteCentreY = 0;
  40451. /**
  40452. * Vignette weight or intensity of the vignette effect.
  40453. */
  40454. this.vignetteWeight = 1.5;
  40455. /**
  40456. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40457. * if vignetteEnabled is set to true.
  40458. */
  40459. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40460. /**
  40461. * Camera field of view used by the Vignette effect.
  40462. */
  40463. this.vignetteCameraFov = 0.5;
  40464. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40465. this._vignetteEnabled = false;
  40466. this._applyByPostProcess = false;
  40467. this._isEnabled = true;
  40468. /**
  40469. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40470. */
  40471. this.onUpdateParameters = new BABYLON.Observable();
  40472. }
  40473. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40474. /**
  40475. * Gets wether the color curves effect is enabled.
  40476. */
  40477. get: function () {
  40478. return this._colorCurvesEnabled;
  40479. },
  40480. /**
  40481. * Sets wether the color curves effect is enabled.
  40482. */
  40483. set: function (value) {
  40484. if (this._colorCurvesEnabled === value) {
  40485. return;
  40486. }
  40487. this._colorCurvesEnabled = value;
  40488. this._updateParameters();
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40494. /**
  40495. * Gets wether the color grading effect is enabled.
  40496. */
  40497. get: function () {
  40498. return this._colorGradingEnabled;
  40499. },
  40500. /**
  40501. * Sets wether the color grading effect is enabled.
  40502. */
  40503. set: function (value) {
  40504. if (this._colorGradingEnabled === value) {
  40505. return;
  40506. }
  40507. this._colorGradingEnabled = value;
  40508. this._updateParameters();
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40514. /**
  40515. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40516. */
  40517. get: function () {
  40518. return this._colorGradingWithGreenDepth;
  40519. },
  40520. /**
  40521. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40522. */
  40523. set: function (value) {
  40524. if (this._colorGradingWithGreenDepth === value) {
  40525. return;
  40526. }
  40527. this._colorGradingWithGreenDepth = value;
  40528. this._updateParameters();
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40534. /**
  40535. * Gets wether the color grading texture contains BGR values.
  40536. */
  40537. get: function () {
  40538. return this._colorGradingBGR;
  40539. },
  40540. /**
  40541. * Sets wether the color grading texture contains BGR values.
  40542. */
  40543. set: function (value) {
  40544. if (this._colorGradingBGR === value) {
  40545. return;
  40546. }
  40547. this._colorGradingBGR = value;
  40548. this._updateParameters();
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40554. /**
  40555. * Gets the Exposure used in the effect.
  40556. */
  40557. get: function () {
  40558. return this._exposure;
  40559. },
  40560. /**
  40561. * Sets the Exposure used in the effect.
  40562. */
  40563. set: function (value) {
  40564. if (this._exposure === value) {
  40565. return;
  40566. }
  40567. this._exposure = value;
  40568. this._updateParameters();
  40569. },
  40570. enumerable: true,
  40571. configurable: true
  40572. });
  40573. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40574. /**
  40575. * Gets wether the tone mapping effect is enabled.
  40576. */
  40577. get: function () {
  40578. return this._toneMappingEnabled;
  40579. },
  40580. /**
  40581. * Sets wether the tone mapping effect is enabled.
  40582. */
  40583. set: function (value) {
  40584. if (this._toneMappingEnabled === value) {
  40585. return;
  40586. }
  40587. this._toneMappingEnabled = value;
  40588. this._updateParameters();
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40594. /**
  40595. * Gets the contrast used in the effect.
  40596. */
  40597. get: function () {
  40598. return this._contrast;
  40599. },
  40600. /**
  40601. * Sets the contrast used in the effect.
  40602. */
  40603. set: function (value) {
  40604. if (this._contrast === value) {
  40605. return;
  40606. }
  40607. this._contrast = value;
  40608. this._updateParameters();
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40614. /**
  40615. * Gets the vignette blend mode allowing different kind of effect.
  40616. */
  40617. get: function () {
  40618. return this._vignetteBlendMode;
  40619. },
  40620. /**
  40621. * Sets the vignette blend mode allowing different kind of effect.
  40622. */
  40623. set: function (value) {
  40624. if (this._vignetteBlendMode === value) {
  40625. return;
  40626. }
  40627. this._vignetteBlendMode = value;
  40628. this._updateParameters();
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40634. /**
  40635. * Gets wether the vignette effect is enabled.
  40636. */
  40637. get: function () {
  40638. return this._vignetteEnabled;
  40639. },
  40640. /**
  40641. * Sets wether the vignette effect is enabled.
  40642. */
  40643. set: function (value) {
  40644. if (this._vignetteEnabled === value) {
  40645. return;
  40646. }
  40647. this._vignetteEnabled = value;
  40648. this._updateParameters();
  40649. },
  40650. enumerable: true,
  40651. configurable: true
  40652. });
  40653. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40654. /**
  40655. * Gets wether the image processing is applied through a post process or not.
  40656. */
  40657. get: function () {
  40658. return this._applyByPostProcess;
  40659. },
  40660. /**
  40661. * Sets wether the image processing is applied through a post process or not.
  40662. */
  40663. set: function (value) {
  40664. if (this._applyByPostProcess === value) {
  40665. return;
  40666. }
  40667. this._applyByPostProcess = value;
  40668. this._updateParameters();
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40674. /**
  40675. * Gets wether the image processing is enabled or not.
  40676. */
  40677. get: function () {
  40678. return this._isEnabled;
  40679. },
  40680. /**
  40681. * Sets wether the image processing is enabled or not.
  40682. */
  40683. set: function (value) {
  40684. if (this._isEnabled === value) {
  40685. return;
  40686. }
  40687. this._isEnabled = value;
  40688. this._updateParameters();
  40689. },
  40690. enumerable: true,
  40691. configurable: true
  40692. });
  40693. /**
  40694. * Method called each time the image processing information changes requires to recompile the effect.
  40695. */
  40696. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40697. this.onUpdateParameters.notifyObservers(this);
  40698. };
  40699. ImageProcessingConfiguration.prototype.getClassName = function () {
  40700. return "ImageProcessingConfiguration";
  40701. };
  40702. /**
  40703. * Prepare the list of uniforms associated with the Image Processing effects.
  40704. * @param uniformsList The list of uniforms used in the effect
  40705. * @param defines the list of defines currently in use
  40706. */
  40707. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40708. if (defines.EXPOSURE) {
  40709. uniforms.push("exposureLinear");
  40710. }
  40711. if (defines.CONTRAST) {
  40712. uniforms.push("contrast");
  40713. }
  40714. if (defines.COLORGRADING) {
  40715. uniforms.push("colorTransformSettings");
  40716. }
  40717. if (defines.VIGNETTE) {
  40718. uniforms.push("vInverseScreenSize");
  40719. uniforms.push("vignetteSettings1");
  40720. uniforms.push("vignetteSettings2");
  40721. }
  40722. if (defines.COLORCURVES) {
  40723. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40724. }
  40725. };
  40726. /**
  40727. * Prepare the list of samplers associated with the Image Processing effects.
  40728. * @param uniformsList The list of uniforms used in the effect
  40729. * @param defines the list of defines currently in use
  40730. */
  40731. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40732. if (defines.COLORGRADING) {
  40733. samplersList.push("txColorTransform");
  40734. }
  40735. };
  40736. /**
  40737. * Prepare the list of defines associated to the shader.
  40738. * @param defines the list of defines to complete
  40739. */
  40740. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40741. if (forPostProcess === void 0) { forPostProcess = false; }
  40742. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40743. defines.VIGNETTE = false;
  40744. defines.TONEMAPPING = false;
  40745. defines.CONTRAST = false;
  40746. defines.EXPOSURE = false;
  40747. defines.COLORCURVES = false;
  40748. defines.COLORGRADING = false;
  40749. defines.COLORGRADING3D = false;
  40750. defines.IMAGEPROCESSING = false;
  40751. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40752. return;
  40753. }
  40754. defines.VIGNETTE = this.vignetteEnabled;
  40755. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40756. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40757. defines.TONEMAPPING = this.toneMappingEnabled;
  40758. defines.CONTRAST = (this.contrast !== 1.0);
  40759. defines.EXPOSURE = (this.exposure !== 1.0);
  40760. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40761. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40762. if (defines.COLORGRADING) {
  40763. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40764. }
  40765. else {
  40766. defines.COLORGRADING3D = false;
  40767. }
  40768. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40769. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40770. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40771. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40772. };
  40773. /**
  40774. * Returns true if all the image processing information are ready.
  40775. */
  40776. ImageProcessingConfiguration.prototype.isReady = function () {
  40777. // Color Grading texure can not be none blocking.
  40778. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40779. };
  40780. /**
  40781. * Binds the image processing to the shader.
  40782. * @param effect The effect to bind to
  40783. */
  40784. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40785. if (aspectRatio === void 0) { aspectRatio = 1; }
  40786. // Color Curves
  40787. if (this._colorCurvesEnabled && this.colorCurves) {
  40788. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40789. }
  40790. // Vignette
  40791. if (this._vignetteEnabled) {
  40792. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40793. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40794. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40795. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40796. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40797. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40798. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40799. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40800. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40801. var vignettePower = -2.0 * this.vignetteWeight;
  40802. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40803. }
  40804. // Exposure
  40805. effect.setFloat("exposureLinear", this.exposure);
  40806. // Contrast
  40807. effect.setFloat("contrast", this.contrast);
  40808. // Color transform settings
  40809. if (this.colorGradingTexture) {
  40810. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40811. var textureSize = this.colorGradingTexture.getSize().height;
  40812. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40813. 0.5 / textureSize, // textureOffset
  40814. textureSize, // textureSize
  40815. this.colorGradingTexture.level // weight
  40816. );
  40817. }
  40818. };
  40819. /**
  40820. * Clones the current image processing instance.
  40821. * @return The cloned image processing
  40822. */
  40823. ImageProcessingConfiguration.prototype.clone = function () {
  40824. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40825. };
  40826. /**
  40827. * Serializes the current image processing instance to a json representation.
  40828. * @return a JSON representation
  40829. */
  40830. ImageProcessingConfiguration.prototype.serialize = function () {
  40831. return BABYLON.SerializationHelper.Serialize(this);
  40832. };
  40833. /**
  40834. * Parses the image processing from a json representation.
  40835. * @param source the JSON source to parse
  40836. * @return The parsed image processing
  40837. */
  40838. ImageProcessingConfiguration.Parse = function (source) {
  40839. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40840. };
  40841. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40842. /**
  40843. * Used to apply the vignette as a mix with the pixel color.
  40844. */
  40845. get: function () {
  40846. return this._VIGNETTEMODE_MULTIPLY;
  40847. },
  40848. enumerable: true,
  40849. configurable: true
  40850. });
  40851. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40852. /**
  40853. * Used to apply the vignette as a replacement of the pixel color.
  40854. */
  40855. get: function () {
  40856. return this._VIGNETTEMODE_OPAQUE;
  40857. },
  40858. enumerable: true,
  40859. configurable: true
  40860. });
  40861. // Static constants associated to the image processing.
  40862. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40863. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40864. __decorate([
  40865. BABYLON.serializeAsColorCurves()
  40866. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40867. __decorate([
  40868. BABYLON.serialize()
  40869. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40870. __decorate([
  40871. BABYLON.serializeAsTexture()
  40872. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40873. __decorate([
  40874. BABYLON.serialize()
  40875. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40876. __decorate([
  40877. BABYLON.serialize()
  40878. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40879. __decorate([
  40880. BABYLON.serialize()
  40881. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40882. __decorate([
  40883. BABYLON.serialize()
  40884. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40885. __decorate([
  40886. BABYLON.serialize()
  40887. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40888. __decorate([
  40889. BABYLON.serialize()
  40890. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40891. __decorate([
  40892. BABYLON.serialize()
  40893. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40894. __decorate([
  40895. BABYLON.serialize()
  40896. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40897. __decorate([
  40898. BABYLON.serialize()
  40899. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40900. __decorate([
  40901. BABYLON.serialize()
  40902. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40903. __decorate([
  40904. BABYLON.serializeAsColor4()
  40905. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40906. __decorate([
  40907. BABYLON.serialize()
  40908. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40909. __decorate([
  40910. BABYLON.serialize()
  40911. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40912. __decorate([
  40913. BABYLON.serialize()
  40914. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40915. __decorate([
  40916. BABYLON.serialize()
  40917. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40918. __decorate([
  40919. BABYLON.serialize()
  40920. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40921. return ImageProcessingConfiguration;
  40922. }());
  40923. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40924. })(BABYLON || (BABYLON = {}));
  40925. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40926. var BABYLON;
  40927. (function (BABYLON) {
  40928. /**
  40929. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40930. * It can help converting any input color in a desired output one. This can then be used to create effects
  40931. * from sepia, black and white to sixties or futuristic rendering...
  40932. *
  40933. * The only supported format is currently 3dl.
  40934. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40935. */
  40936. var ColorGradingTexture = /** @class */ (function (_super) {
  40937. __extends(ColorGradingTexture, _super);
  40938. /**
  40939. * Instantiates a ColorGradingTexture from the following parameters.
  40940. *
  40941. * @param url The location of the color gradind data (currently only supporting 3dl)
  40942. * @param scene The scene the texture will be used in
  40943. */
  40944. function ColorGradingTexture(url, scene) {
  40945. var _this = _super.call(this, scene) || this;
  40946. if (!url) {
  40947. return _this;
  40948. }
  40949. _this._engine = scene.getEngine();
  40950. _this._textureMatrix = BABYLON.Matrix.Identity();
  40951. _this.name = url;
  40952. _this.url = url;
  40953. _this.hasAlpha = false;
  40954. _this.isCube = false;
  40955. _this.is3D = _this._engine.webGLVersion > 1;
  40956. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40957. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40958. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40959. _this.anisotropicFilteringLevel = 1;
  40960. _this._texture = _this._getFromCache(url, true);
  40961. if (!_this._texture) {
  40962. if (!scene.useDelayedTextureLoading) {
  40963. _this.loadTexture();
  40964. }
  40965. else {
  40966. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40967. }
  40968. }
  40969. return _this;
  40970. }
  40971. /**
  40972. * Returns the texture matrix used in most of the material.
  40973. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40974. */
  40975. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40976. return this._textureMatrix;
  40977. };
  40978. /**
  40979. * Occurs when the file being loaded is a .3dl LUT file.
  40980. */
  40981. ColorGradingTexture.prototype.load3dlTexture = function () {
  40982. var engine = this._engine;
  40983. var texture;
  40984. if (engine.webGLVersion === 1) {
  40985. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40986. }
  40987. else {
  40988. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40989. }
  40990. this._texture = texture;
  40991. var callback = function (text) {
  40992. if (typeof text !== "string") {
  40993. return;
  40994. }
  40995. var data = null;
  40996. var tempData = null;
  40997. var line;
  40998. var lines = text.split('\n');
  40999. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41000. var maxColor = 0;
  41001. for (var i = 0; i < lines.length; i++) {
  41002. line = lines[i];
  41003. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41004. continue;
  41005. if (line.indexOf('#') === 0)
  41006. continue;
  41007. var words = line.split(" ");
  41008. if (size === 0) {
  41009. // Number of space + one
  41010. size = words.length;
  41011. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41012. tempData = new Float32Array(size * size * size * 4);
  41013. continue;
  41014. }
  41015. if (size != 0) {
  41016. var r = Math.max(parseInt(words[0]), 0);
  41017. var g = Math.max(parseInt(words[1]), 0);
  41018. var b = Math.max(parseInt(words[2]), 0);
  41019. maxColor = Math.max(r, maxColor);
  41020. maxColor = Math.max(g, maxColor);
  41021. maxColor = Math.max(b, maxColor);
  41022. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41023. if (tempData) {
  41024. tempData[pixelStorageIndex + 0] = r;
  41025. tempData[pixelStorageIndex + 1] = g;
  41026. tempData[pixelStorageIndex + 2] = b;
  41027. }
  41028. pixelIndexSlice++;
  41029. if (pixelIndexSlice % size == 0) {
  41030. pixelIndexH++;
  41031. pixelIndexSlice = 0;
  41032. if (pixelIndexH % size == 0) {
  41033. pixelIndexW++;
  41034. pixelIndexH = 0;
  41035. }
  41036. }
  41037. }
  41038. }
  41039. if (tempData && data) {
  41040. for (var i = 0; i < tempData.length; i++) {
  41041. if (i > 0 && (i + 1) % 4 === 0) {
  41042. data[i] = 255;
  41043. }
  41044. else {
  41045. var value = tempData[i];
  41046. data[i] = (value / maxColor * 255);
  41047. }
  41048. }
  41049. }
  41050. if (texture.is3D) {
  41051. texture.updateSize(size, size, size);
  41052. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41053. }
  41054. else {
  41055. texture.updateSize(size * size, size);
  41056. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41057. }
  41058. };
  41059. var scene = this.getScene();
  41060. if (scene) {
  41061. scene._loadFile(this.url, callback);
  41062. }
  41063. else {
  41064. this._engine._loadFile(this.url, callback);
  41065. }
  41066. return this._texture;
  41067. };
  41068. /**
  41069. * Starts the loading process of the texture.
  41070. */
  41071. ColorGradingTexture.prototype.loadTexture = function () {
  41072. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41073. this.load3dlTexture();
  41074. }
  41075. };
  41076. /**
  41077. * Clones the color gradind texture.
  41078. */
  41079. ColorGradingTexture.prototype.clone = function () {
  41080. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41081. // Base texture
  41082. newTexture.level = this.level;
  41083. return newTexture;
  41084. };
  41085. /**
  41086. * Called during delayed load for textures.
  41087. */
  41088. ColorGradingTexture.prototype.delayLoad = function () {
  41089. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41090. return;
  41091. }
  41092. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41093. this._texture = this._getFromCache(this.url, true);
  41094. if (!this._texture) {
  41095. this.loadTexture();
  41096. }
  41097. };
  41098. /**
  41099. * Parses a color grading texture serialized by Babylon.
  41100. * @param parsedTexture The texture information being parsedTexture
  41101. * @param scene The scene to load the texture in
  41102. * @param rootUrl The root url of the data assets to load
  41103. * @return A color gradind texture
  41104. */
  41105. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41106. var texture = null;
  41107. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41108. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41109. texture.name = parsedTexture.name;
  41110. texture.level = parsedTexture.level;
  41111. }
  41112. return texture;
  41113. };
  41114. /**
  41115. * Serializes the LUT texture to json format.
  41116. */
  41117. ColorGradingTexture.prototype.serialize = function () {
  41118. if (!this.name) {
  41119. return null;
  41120. }
  41121. var serializationObject = {};
  41122. serializationObject.name = this.name;
  41123. serializationObject.level = this.level;
  41124. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41125. return serializationObject;
  41126. };
  41127. /**
  41128. * Empty line regex stored for GC.
  41129. */
  41130. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41131. return ColorGradingTexture;
  41132. }(BABYLON.BaseTexture));
  41133. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41134. })(BABYLON || (BABYLON = {}));
  41135. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41136. var BABYLON;
  41137. (function (BABYLON) {
  41138. /**
  41139. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41140. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41141. * 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;
  41142. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41143. */
  41144. var ColorCurves = /** @class */ (function () {
  41145. function ColorCurves() {
  41146. this._dirty = true;
  41147. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41148. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41149. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41150. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41151. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41152. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41153. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41154. this._globalHue = 30;
  41155. this._globalDensity = 0;
  41156. this._globalSaturation = 0;
  41157. this._globalExposure = 0;
  41158. this._highlightsHue = 30;
  41159. this._highlightsDensity = 0;
  41160. this._highlightsSaturation = 0;
  41161. this._highlightsExposure = 0;
  41162. this._midtonesHue = 30;
  41163. this._midtonesDensity = 0;
  41164. this._midtonesSaturation = 0;
  41165. this._midtonesExposure = 0;
  41166. this._shadowsHue = 30;
  41167. this._shadowsDensity = 0;
  41168. this._shadowsSaturation = 0;
  41169. this._shadowsExposure = 0;
  41170. }
  41171. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41172. /**
  41173. * Gets the global Hue value.
  41174. * 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).
  41175. */
  41176. get: function () {
  41177. return this._globalHue;
  41178. },
  41179. /**
  41180. * Sets the global Hue value.
  41181. * 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).
  41182. */
  41183. set: function (value) {
  41184. this._globalHue = value;
  41185. this._dirty = true;
  41186. },
  41187. enumerable: true,
  41188. configurable: true
  41189. });
  41190. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41191. /**
  41192. * Gets the global Density value.
  41193. * 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.
  41194. * Values less than zero provide a filter of opposite hue.
  41195. */
  41196. get: function () {
  41197. return this._globalDensity;
  41198. },
  41199. /**
  41200. * Sets the global Density value.
  41201. * 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.
  41202. * Values less than zero provide a filter of opposite hue.
  41203. */
  41204. set: function (value) {
  41205. this._globalDensity = value;
  41206. this._dirty = true;
  41207. },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41212. /**
  41213. * Gets the global Saturation value.
  41214. * 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.
  41215. */
  41216. get: function () {
  41217. return this._globalSaturation;
  41218. },
  41219. /**
  41220. * Sets the global Saturation value.
  41221. * 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.
  41222. */
  41223. set: function (value) {
  41224. this._globalSaturation = value;
  41225. this._dirty = true;
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41231. /**
  41232. * Gets the highlights Hue value.
  41233. * 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).
  41234. */
  41235. get: function () {
  41236. return this._highlightsHue;
  41237. },
  41238. /**
  41239. * Sets the highlights Hue value.
  41240. * 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).
  41241. */
  41242. set: function (value) {
  41243. this._highlightsHue = value;
  41244. this._dirty = true;
  41245. },
  41246. enumerable: true,
  41247. configurable: true
  41248. });
  41249. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41250. /**
  41251. * Gets the highlights Density value.
  41252. * 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.
  41253. * Values less than zero provide a filter of opposite hue.
  41254. */
  41255. get: function () {
  41256. return this._highlightsDensity;
  41257. },
  41258. /**
  41259. * Sets the highlights Density value.
  41260. * 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.
  41261. * Values less than zero provide a filter of opposite hue.
  41262. */
  41263. set: function (value) {
  41264. this._highlightsDensity = value;
  41265. this._dirty = true;
  41266. },
  41267. enumerable: true,
  41268. configurable: true
  41269. });
  41270. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41271. /**
  41272. * Gets the highlights Saturation value.
  41273. * 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.
  41274. */
  41275. get: function () {
  41276. return this._highlightsSaturation;
  41277. },
  41278. /**
  41279. * Sets the highlights Saturation value.
  41280. * 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.
  41281. */
  41282. set: function (value) {
  41283. this._highlightsSaturation = value;
  41284. this._dirty = true;
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41290. /**
  41291. * Gets the highlights Exposure value.
  41292. * 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.
  41293. */
  41294. get: function () {
  41295. return this._highlightsExposure;
  41296. },
  41297. /**
  41298. * Sets the highlights Exposure value.
  41299. * 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.
  41300. */
  41301. set: function (value) {
  41302. this._highlightsExposure = value;
  41303. this._dirty = true;
  41304. },
  41305. enumerable: true,
  41306. configurable: true
  41307. });
  41308. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41309. /**
  41310. * Gets the midtones Hue value.
  41311. * 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).
  41312. */
  41313. get: function () {
  41314. return this._midtonesHue;
  41315. },
  41316. /**
  41317. * Sets the midtones Hue value.
  41318. * 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).
  41319. */
  41320. set: function (value) {
  41321. this._midtonesHue = value;
  41322. this._dirty = true;
  41323. },
  41324. enumerable: true,
  41325. configurable: true
  41326. });
  41327. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41328. /**
  41329. * Gets the midtones Density value.
  41330. * 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.
  41331. * Values less than zero provide a filter of opposite hue.
  41332. */
  41333. get: function () {
  41334. return this._midtonesDensity;
  41335. },
  41336. /**
  41337. * Sets the midtones Density value.
  41338. * 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.
  41339. * Values less than zero provide a filter of opposite hue.
  41340. */
  41341. set: function (value) {
  41342. this._midtonesDensity = value;
  41343. this._dirty = true;
  41344. },
  41345. enumerable: true,
  41346. configurable: true
  41347. });
  41348. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41349. /**
  41350. * Gets the midtones Saturation value.
  41351. * 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.
  41352. */
  41353. get: function () {
  41354. return this._midtonesSaturation;
  41355. },
  41356. /**
  41357. * Sets the midtones Saturation value.
  41358. * 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.
  41359. */
  41360. set: function (value) {
  41361. this._midtonesSaturation = value;
  41362. this._dirty = true;
  41363. },
  41364. enumerable: true,
  41365. configurable: true
  41366. });
  41367. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41368. /**
  41369. * Gets the midtones Exposure value.
  41370. * 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.
  41371. */
  41372. get: function () {
  41373. return this._midtonesExposure;
  41374. },
  41375. /**
  41376. * Sets the midtones Exposure value.
  41377. * 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.
  41378. */
  41379. set: function (value) {
  41380. this._midtonesExposure = value;
  41381. this._dirty = true;
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41387. /**
  41388. * Gets the shadows Hue value.
  41389. * 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).
  41390. */
  41391. get: function () {
  41392. return this._shadowsHue;
  41393. },
  41394. /**
  41395. * Sets the shadows Hue value.
  41396. * 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).
  41397. */
  41398. set: function (value) {
  41399. this._shadowsHue = value;
  41400. this._dirty = true;
  41401. },
  41402. enumerable: true,
  41403. configurable: true
  41404. });
  41405. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41406. /**
  41407. * Gets the shadows Density value.
  41408. * 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.
  41409. * Values less than zero provide a filter of opposite hue.
  41410. */
  41411. get: function () {
  41412. return this._shadowsDensity;
  41413. },
  41414. /**
  41415. * Sets the shadows Density value.
  41416. * 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.
  41417. * Values less than zero provide a filter of opposite hue.
  41418. */
  41419. set: function (value) {
  41420. this._shadowsDensity = value;
  41421. this._dirty = true;
  41422. },
  41423. enumerable: true,
  41424. configurable: true
  41425. });
  41426. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41427. /**
  41428. * Gets the shadows Saturation value.
  41429. * 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.
  41430. */
  41431. get: function () {
  41432. return this._shadowsSaturation;
  41433. },
  41434. /**
  41435. * Sets the shadows Saturation value.
  41436. * 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.
  41437. */
  41438. set: function (value) {
  41439. this._shadowsSaturation = value;
  41440. this._dirty = true;
  41441. },
  41442. enumerable: true,
  41443. configurable: true
  41444. });
  41445. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41446. /**
  41447. * Gets the shadows Exposure value.
  41448. * 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.
  41449. */
  41450. get: function () {
  41451. return this._shadowsExposure;
  41452. },
  41453. /**
  41454. * Sets the shadows Exposure value.
  41455. * 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.
  41456. */
  41457. set: function (value) {
  41458. this._shadowsExposure = value;
  41459. this._dirty = true;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. ColorCurves.prototype.getClassName = function () {
  41465. return "ColorCurves";
  41466. };
  41467. /**
  41468. * Binds the color curves to the shader.
  41469. * @param colorCurves The color curve to bind
  41470. * @param effect The effect to bind to
  41471. */
  41472. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41473. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41474. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41475. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41476. if (colorCurves._dirty) {
  41477. colorCurves._dirty = false;
  41478. // Fill in global info.
  41479. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41480. // Compute highlights info.
  41481. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41482. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41483. // Compute midtones info.
  41484. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41485. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41486. // Compute shadows info.
  41487. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41488. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41489. // Compute deltas (neutral is midtones).
  41490. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41491. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41492. }
  41493. if (effect) {
  41494. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41495. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41496. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41497. }
  41498. };
  41499. /**
  41500. * Prepare the list of uniforms associated with the ColorCurves effects.
  41501. * @param uniformsList The list of uniforms used in the effect
  41502. */
  41503. ColorCurves.PrepareUniforms = function (uniformsList) {
  41504. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41505. };
  41506. /**
  41507. * Returns color grading data based on a hue, density, saturation and exposure value.
  41508. * @param filterHue The hue of the color filter.
  41509. * @param filterDensity The density of the color filter.
  41510. * @param saturation The saturation.
  41511. * @param exposure The exposure.
  41512. * @param result The result data container.
  41513. */
  41514. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41515. if (hue == null) {
  41516. return;
  41517. }
  41518. hue = ColorCurves.clamp(hue, 0, 360);
  41519. density = ColorCurves.clamp(density, -100, 100);
  41520. saturation = ColorCurves.clamp(saturation, -100, 100);
  41521. exposure = ColorCurves.clamp(exposure, -100, 100);
  41522. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41523. // so that the maximum filter density is only 50% control. This provides fine control
  41524. // for small values and reasonable range.
  41525. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41526. density *= 0.5;
  41527. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41528. if (density < 0) {
  41529. density *= -1;
  41530. hue = (hue + 180) % 360;
  41531. }
  41532. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41533. result.scaleToRef(2, result);
  41534. result.a = 1 + 0.01 * saturation;
  41535. };
  41536. /**
  41537. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41538. * @param value The input slider value in range [-100,100].
  41539. * @returns Adjusted value.
  41540. */
  41541. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41542. value /= 100;
  41543. var x = Math.abs(value);
  41544. x = Math.pow(x, 2);
  41545. if (value < 0) {
  41546. x *= -1;
  41547. }
  41548. x *= 100;
  41549. return x;
  41550. };
  41551. /**
  41552. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41553. * @param hue The hue (H) input.
  41554. * @param saturation The saturation (S) input.
  41555. * @param brightness The brightness (B) input.
  41556. * @result An RGBA color represented as Vector4.
  41557. */
  41558. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41559. var h = ColorCurves.clamp(hue, 0, 360);
  41560. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41561. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41562. if (s === 0) {
  41563. result.r = v;
  41564. result.g = v;
  41565. result.b = v;
  41566. }
  41567. else {
  41568. // sector 0 to 5
  41569. h /= 60;
  41570. var i = Math.floor(h);
  41571. // fractional part of h
  41572. var f = h - i;
  41573. var p = v * (1 - s);
  41574. var q = v * (1 - s * f);
  41575. var t = v * (1 - s * (1 - f));
  41576. switch (i) {
  41577. case 0:
  41578. result.r = v;
  41579. result.g = t;
  41580. result.b = p;
  41581. break;
  41582. case 1:
  41583. result.r = q;
  41584. result.g = v;
  41585. result.b = p;
  41586. break;
  41587. case 2:
  41588. result.r = p;
  41589. result.g = v;
  41590. result.b = t;
  41591. break;
  41592. case 3:
  41593. result.r = p;
  41594. result.g = q;
  41595. result.b = v;
  41596. break;
  41597. case 4:
  41598. result.r = t;
  41599. result.g = p;
  41600. result.b = v;
  41601. break;
  41602. default: // case 5:
  41603. result.r = v;
  41604. result.g = p;
  41605. result.b = q;
  41606. break;
  41607. }
  41608. }
  41609. result.a = 1;
  41610. };
  41611. /**
  41612. * Returns a value clamped between min and max
  41613. * @param value The value to clamp
  41614. * @param min The minimum of value
  41615. * @param max The maximum of value
  41616. * @returns The clamped value.
  41617. */
  41618. ColorCurves.clamp = function (value, min, max) {
  41619. return Math.min(Math.max(value, min), max);
  41620. };
  41621. /**
  41622. * Clones the current color curve instance.
  41623. * @return The cloned curves
  41624. */
  41625. ColorCurves.prototype.clone = function () {
  41626. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41627. };
  41628. /**
  41629. * Serializes the current color curve instance to a json representation.
  41630. * @return a JSON representation
  41631. */
  41632. ColorCurves.prototype.serialize = function () {
  41633. return BABYLON.SerializationHelper.Serialize(this);
  41634. };
  41635. /**
  41636. * Parses the color curve from a json representation.
  41637. * @param source the JSON source to parse
  41638. * @return The parsed curves
  41639. */
  41640. ColorCurves.Parse = function (source) {
  41641. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41642. };
  41643. __decorate([
  41644. BABYLON.serialize()
  41645. ], ColorCurves.prototype, "_globalHue", void 0);
  41646. __decorate([
  41647. BABYLON.serialize()
  41648. ], ColorCurves.prototype, "_globalDensity", void 0);
  41649. __decorate([
  41650. BABYLON.serialize()
  41651. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41652. __decorate([
  41653. BABYLON.serialize()
  41654. ], ColorCurves.prototype, "_globalExposure", void 0);
  41655. __decorate([
  41656. BABYLON.serialize()
  41657. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41658. __decorate([
  41659. BABYLON.serialize()
  41660. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41661. __decorate([
  41662. BABYLON.serialize()
  41663. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41664. __decorate([
  41665. BABYLON.serialize()
  41666. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41667. __decorate([
  41668. BABYLON.serialize()
  41669. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41670. __decorate([
  41671. BABYLON.serialize()
  41672. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41673. __decorate([
  41674. BABYLON.serialize()
  41675. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41676. __decorate([
  41677. BABYLON.serialize()
  41678. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41679. return ColorCurves;
  41680. }());
  41681. BABYLON.ColorCurves = ColorCurves;
  41682. })(BABYLON || (BABYLON = {}));
  41683. //# sourceMappingURL=babylon.colorCurves.js.map
  41684. //# sourceMappingURL=babylon.behavior.js.map
  41685. var BABYLON;
  41686. (function (BABYLON) {
  41687. /**
  41688. * "Static Class" containing the most commonly used helper while dealing with material for
  41689. * rendering purpose.
  41690. *
  41691. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41692. *
  41693. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41694. */
  41695. var MaterialHelper = /** @class */ (function () {
  41696. function MaterialHelper() {
  41697. }
  41698. /**
  41699. * Bind the current view position to an effect.
  41700. * @param effect The effect to be bound
  41701. * @param scene The scene the eyes position is used from
  41702. */
  41703. MaterialHelper.BindEyePosition = function (effect, scene) {
  41704. if (scene._forcedViewPosition) {
  41705. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41706. return;
  41707. }
  41708. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41709. };
  41710. /**
  41711. * Helps preparing the defines values about the UVs in used in the effect.
  41712. * UVs are shared as much as we can accross chanels in the shaders.
  41713. * @param texture The texture we are preparing the UVs for
  41714. * @param defines The defines to update
  41715. * @param key The chanel key "diffuse", "specular"... used in the shader
  41716. */
  41717. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41718. defines._needUVs = true;
  41719. defines[key] = true;
  41720. if (texture.getTextureMatrix().isIdentity(true)) {
  41721. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41722. if (texture.coordinatesIndex === 0) {
  41723. defines["MAINUV1"] = true;
  41724. }
  41725. else {
  41726. defines["MAINUV2"] = true;
  41727. }
  41728. }
  41729. else {
  41730. defines[key + "DIRECTUV"] = 0;
  41731. }
  41732. };
  41733. /**
  41734. * Binds a texture matrix value to its corrsponding uniform
  41735. * @param texture The texture to bind the matrix for
  41736. * @param uniformBuffer The uniform buffer receivin the data
  41737. * @param key The chanel key "diffuse", "specular"... used in the shader
  41738. */
  41739. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41740. var matrix = texture.getTextureMatrix();
  41741. if (!matrix.isIdentity(true)) {
  41742. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41743. }
  41744. };
  41745. /**
  41746. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41747. * @param mesh defines the current mesh
  41748. * @param scene defines the current scene
  41749. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41750. * @param pointsCloud defines if point cloud rendering has to be turned on
  41751. * @param fogEnabled defines if fog has to be turned on
  41752. * @param alphaTest defines if alpha testing has to be turned on
  41753. * @param defines defines the current list of defines
  41754. */
  41755. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41756. if (defines._areMiscDirty) {
  41757. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41758. defines["POINTSIZE"] = pointsCloud;
  41759. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41760. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41761. defines["ALPHATEST"] = alphaTest;
  41762. }
  41763. };
  41764. /**
  41765. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41766. * @param scene defines the current scene
  41767. * @param engine defines the current engine
  41768. * @param defines specifies the list of active defines
  41769. * @param useInstances defines if instances have to be turned on
  41770. * @param useClipPlane defines if clip plane have to be turned on
  41771. */
  41772. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41773. if (useClipPlane === void 0) { useClipPlane = null; }
  41774. var changed = false;
  41775. if (useClipPlane == null) {
  41776. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41777. }
  41778. if (defines["CLIPPLANE"] !== useClipPlane) {
  41779. defines["CLIPPLANE"] = useClipPlane;
  41780. changed = true;
  41781. }
  41782. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41783. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41784. changed = true;
  41785. }
  41786. if (defines["INSTANCES"] !== useInstances) {
  41787. defines["INSTANCES"] = useInstances;
  41788. changed = true;
  41789. }
  41790. if (changed) {
  41791. defines.markAsUnprocessed();
  41792. }
  41793. };
  41794. /**
  41795. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41796. * @param mesh The mesh containing the geometry data we will draw
  41797. * @param defines The defines to update
  41798. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41799. * @param useBones Precise whether bones should be used or not (override mesh info)
  41800. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41801. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41802. * @returns false if defines are considered not dirty and have not been checked
  41803. */
  41804. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41805. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41806. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41807. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41808. return false;
  41809. }
  41810. defines._normals = defines._needNormals;
  41811. defines._uvs = defines._needUVs;
  41812. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41813. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41814. defines["TANGENT"] = true;
  41815. }
  41816. if (defines._needUVs) {
  41817. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41818. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41819. }
  41820. else {
  41821. defines["UV1"] = false;
  41822. defines["UV2"] = false;
  41823. }
  41824. if (useVertexColor) {
  41825. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41826. defines["VERTEXCOLOR"] = hasVertexColors;
  41827. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41828. }
  41829. if (useBones) {
  41830. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41831. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41832. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41833. }
  41834. else {
  41835. defines["NUM_BONE_INFLUENCERS"] = 0;
  41836. defines["BonesPerMesh"] = 0;
  41837. }
  41838. }
  41839. if (useMorphTargets) {
  41840. var manager = mesh.morphTargetManager;
  41841. if (manager) {
  41842. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41843. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41844. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41845. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41846. }
  41847. else {
  41848. defines["MORPHTARGETS_TANGENT"] = false;
  41849. defines["MORPHTARGETS_NORMAL"] = false;
  41850. defines["MORPHTARGETS"] = false;
  41851. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41852. }
  41853. }
  41854. return true;
  41855. };
  41856. /**
  41857. * Prepares the defines related to the light information passed in parameter
  41858. * @param scene The scene we are intending to draw
  41859. * @param mesh The mesh the effect is compiling for
  41860. * @param defines The defines to update
  41861. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41862. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41863. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41864. * @returns true if normals will be required for the rest of the effect
  41865. */
  41866. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41867. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41868. if (disableLighting === void 0) { disableLighting = false; }
  41869. if (!defines._areLightsDirty) {
  41870. return defines._needNormals;
  41871. }
  41872. var lightIndex = 0;
  41873. var needNormals = false;
  41874. var needRebuild = false;
  41875. var lightmapMode = false;
  41876. var shadowEnabled = false;
  41877. var specularEnabled = false;
  41878. if (scene.lightsEnabled && !disableLighting) {
  41879. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41880. var light = _a[_i];
  41881. needNormals = true;
  41882. if (defines["LIGHT" + lightIndex] === undefined) {
  41883. needRebuild = true;
  41884. }
  41885. defines["LIGHT" + lightIndex] = true;
  41886. defines["SPOTLIGHT" + lightIndex] = false;
  41887. defines["HEMILIGHT" + lightIndex] = false;
  41888. defines["POINTLIGHT" + lightIndex] = false;
  41889. defines["DIRLIGHT" + lightIndex] = false;
  41890. var type;
  41891. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41892. type = "SPOTLIGHT" + lightIndex;
  41893. var spotLight = light;
  41894. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41895. }
  41896. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41897. type = "HEMILIGHT" + lightIndex;
  41898. }
  41899. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41900. type = "POINTLIGHT" + lightIndex;
  41901. }
  41902. else {
  41903. type = "DIRLIGHT" + lightIndex;
  41904. }
  41905. defines[type] = true;
  41906. // Specular
  41907. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41908. specularEnabled = true;
  41909. }
  41910. // Shadows
  41911. defines["SHADOW" + lightIndex] = false;
  41912. defines["SHADOWPCF" + lightIndex] = false;
  41913. defines["SHADOWPCSS" + lightIndex] = false;
  41914. defines["SHADOWPOISSON" + lightIndex] = false;
  41915. defines["SHADOWESM" + lightIndex] = false;
  41916. defines["SHADOWCUBE" + lightIndex] = false;
  41917. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41918. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41919. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41920. var shadowGenerator = light.getShadowGenerator();
  41921. if (shadowGenerator) {
  41922. shadowEnabled = true;
  41923. shadowGenerator.prepareDefines(defines, lightIndex);
  41924. }
  41925. }
  41926. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41927. lightmapMode = true;
  41928. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41929. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41930. }
  41931. else {
  41932. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41933. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41934. }
  41935. lightIndex++;
  41936. if (lightIndex === maxSimultaneousLights)
  41937. break;
  41938. }
  41939. }
  41940. defines["SPECULARTERM"] = specularEnabled;
  41941. defines["SHADOWS"] = shadowEnabled;
  41942. // Resetting all other lights if any
  41943. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41944. if (defines["LIGHT" + index] !== undefined) {
  41945. defines["LIGHT" + index] = false;
  41946. defines["HEMILIGHT" + lightIndex] = false;
  41947. defines["POINTLIGHT" + lightIndex] = false;
  41948. defines["DIRLIGHT" + lightIndex] = false;
  41949. defines["SPOTLIGHT" + lightIndex] = false;
  41950. defines["SHADOW" + lightIndex] = false;
  41951. }
  41952. }
  41953. var caps = scene.getEngine().getCaps();
  41954. if (defines["SHADOWFLOAT"] === undefined) {
  41955. needRebuild = true;
  41956. }
  41957. defines["SHADOWFLOAT"] = shadowEnabled &&
  41958. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41959. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41960. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41961. if (needRebuild) {
  41962. defines.rebuild();
  41963. }
  41964. return needNormals;
  41965. };
  41966. /**
  41967. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41968. * that won t be acctive due to defines being turned off.
  41969. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41970. * @param samplersList The samplers list
  41971. * @param defines The defines helping in the list generation
  41972. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41973. */
  41974. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41975. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41976. var uniformsList;
  41977. var uniformBuffersList = null;
  41978. if (uniformsListOrOptions.uniformsNames) {
  41979. var options = uniformsListOrOptions;
  41980. uniformsList = options.uniformsNames;
  41981. uniformBuffersList = options.uniformBuffersNames;
  41982. samplersList = options.samplers;
  41983. defines = options.defines;
  41984. maxSimultaneousLights = options.maxSimultaneousLights;
  41985. }
  41986. else {
  41987. uniformsList = uniformsListOrOptions;
  41988. if (!samplersList) {
  41989. samplersList = [];
  41990. }
  41991. }
  41992. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41993. if (!defines["LIGHT" + lightIndex]) {
  41994. break;
  41995. }
  41996. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41997. if (uniformBuffersList) {
  41998. uniformBuffersList.push("Light" + lightIndex);
  41999. }
  42000. samplersList.push("shadowSampler" + lightIndex);
  42001. samplersList.push("depthSampler" + lightIndex);
  42002. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42003. samplersList.push("projectionLightSampler" + lightIndex);
  42004. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42005. }
  42006. }
  42007. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42008. uniformsList.push("morphTargetInfluences");
  42009. }
  42010. };
  42011. /**
  42012. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42013. * @param defines The defines to update while falling back
  42014. * @param fallbacks The authorized effect fallbacks
  42015. * @param maxSimultaneousLights The maximum number of lights allowed
  42016. * @param rank the current rank of the Effect
  42017. * @returns The newly affected rank
  42018. */
  42019. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42020. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42021. if (rank === void 0) { rank = 0; }
  42022. var lightFallbackRank = 0;
  42023. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42024. if (!defines["LIGHT" + lightIndex]) {
  42025. break;
  42026. }
  42027. if (lightIndex > 0) {
  42028. lightFallbackRank = rank + lightIndex;
  42029. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42030. }
  42031. if (!defines["SHADOWS"]) {
  42032. if (defines["SHADOW" + lightIndex]) {
  42033. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42034. }
  42035. if (defines["SHADOWPCF" + lightIndex]) {
  42036. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42037. }
  42038. if (defines["SHADOWPCSS" + lightIndex]) {
  42039. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42040. }
  42041. if (defines["SHADOWPOISSON" + lightIndex]) {
  42042. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42043. }
  42044. if (defines["SHADOWESM" + lightIndex]) {
  42045. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42046. }
  42047. }
  42048. }
  42049. return lightFallbackRank++;
  42050. };
  42051. /**
  42052. * Prepares the list of attributes required for morph targets according to the effect defines.
  42053. * @param attribs The current list of supported attribs
  42054. * @param mesh The mesh to prepare the morph targets attributes for
  42055. * @param defines The current Defines of the effect
  42056. */
  42057. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42058. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42059. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42060. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42061. var manager = mesh.morphTargetManager;
  42062. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42063. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42064. for (var index = 0; index < influencers; index++) {
  42065. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42066. if (normal) {
  42067. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42068. }
  42069. if (tangent) {
  42070. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42071. }
  42072. if (attribs.length > maxAttributesCount) {
  42073. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42074. }
  42075. }
  42076. }
  42077. };
  42078. /**
  42079. * Prepares the list of attributes required for bones according to the effect defines.
  42080. * @param attribs The current list of supported attribs
  42081. * @param mesh The mesh to prepare the bones attributes for
  42082. * @param defines The current Defines of the effect
  42083. * @param fallbacks The current efffect fallback strategy
  42084. */
  42085. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42086. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42087. fallbacks.addCPUSkinningFallback(0, mesh);
  42088. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42089. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42090. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42091. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42092. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42093. }
  42094. }
  42095. };
  42096. /**
  42097. * Prepares the list of attributes required for instances according to the effect defines.
  42098. * @param attribs The current list of supported attribs
  42099. * @param defines The current Defines of the effect
  42100. */
  42101. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42102. if (defines["INSTANCES"]) {
  42103. attribs.push("world0");
  42104. attribs.push("world1");
  42105. attribs.push("world2");
  42106. attribs.push("world3");
  42107. }
  42108. };
  42109. /**
  42110. * Binds the light shadow information to the effect for the given mesh.
  42111. * @param light The light containing the generator
  42112. * @param scene The scene the lights belongs to
  42113. * @param mesh The mesh we are binding the information to render
  42114. * @param lightIndex The light index in the effect used to render the mesh
  42115. * @param effect The effect we are binding the data to
  42116. */
  42117. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42118. if (light.shadowEnabled && mesh.receiveShadows) {
  42119. var shadowGenerator = light.getShadowGenerator();
  42120. if (shadowGenerator) {
  42121. shadowGenerator.bindShadowLight(lightIndex, effect);
  42122. }
  42123. }
  42124. };
  42125. /**
  42126. * Binds the light information to the effect.
  42127. * @param light The light containing the generator
  42128. * @param effect The effect we are binding the data to
  42129. * @param lightIndex The light index in the effect used to render
  42130. */
  42131. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42132. light.transferToEffect(effect, lightIndex + "");
  42133. };
  42134. /**
  42135. * Binds the lights information from the scene to the effect for the given mesh.
  42136. * @param scene The scene the lights belongs to
  42137. * @param mesh The mesh we are binding the information to render
  42138. * @param effect The effect we are binding the data to
  42139. * @param defines The generated defines for the effect
  42140. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42141. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42142. */
  42143. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42144. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42145. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42146. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42147. for (var i = 0; i < len; i++) {
  42148. var light = mesh._lightSources[i];
  42149. var iAsString = i.toString();
  42150. var scaledIntensity = light.getScaledIntensity();
  42151. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42152. MaterialHelper.BindLightProperties(light, effect, i);
  42153. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42154. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42155. if (defines["SPECULARTERM"]) {
  42156. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42157. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42158. }
  42159. // Shadows
  42160. if (scene.shadowsEnabled) {
  42161. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42162. }
  42163. light._uniformBuffer.update();
  42164. }
  42165. };
  42166. /**
  42167. * Binds the fog information from the scene to the effect for the given mesh.
  42168. * @param scene The scene the lights belongs to
  42169. * @param mesh The mesh we are binding the information to render
  42170. * @param effect The effect we are binding the data to
  42171. */
  42172. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42173. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42174. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42175. effect.setColor3("vFogColor", scene.fogColor);
  42176. }
  42177. };
  42178. /**
  42179. * Binds the bones information from the mesh to the effect.
  42180. * @param mesh The mesh we are binding the information to render
  42181. * @param effect The effect we are binding the data to
  42182. */
  42183. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42184. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42185. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42186. if (matrices && effect) {
  42187. effect.setMatrices("mBones", matrices);
  42188. }
  42189. }
  42190. };
  42191. /**
  42192. * Binds the morph targets information from the mesh to the effect.
  42193. * @param abstractMesh The mesh we are binding the information to render
  42194. * @param effect The effect we are binding the data to
  42195. */
  42196. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42197. var manager = abstractMesh.morphTargetManager;
  42198. if (!abstractMesh || !manager) {
  42199. return;
  42200. }
  42201. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42202. };
  42203. /**
  42204. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42205. * @param defines The generated defines used in the effect
  42206. * @param effect The effect we are binding the data to
  42207. * @param scene The scene we are willing to render with logarithmic scale for
  42208. */
  42209. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42210. if (defines["LOGARITHMICDEPTH"]) {
  42211. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42212. }
  42213. };
  42214. /**
  42215. * Binds the clip plane information from the scene to the effect.
  42216. * @param scene The scene the clip plane information are extracted from
  42217. * @param effect The effect we are binding the data to
  42218. */
  42219. MaterialHelper.BindClipPlane = function (effect, scene) {
  42220. if (scene.clipPlane) {
  42221. var clipPlane = scene.clipPlane;
  42222. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42223. }
  42224. };
  42225. return MaterialHelper;
  42226. }());
  42227. BABYLON.MaterialHelper = MaterialHelper;
  42228. })(BABYLON || (BABYLON = {}));
  42229. //# sourceMappingURL=babylon.materialHelper.js.map
  42230. var BABYLON;
  42231. (function (BABYLON) {
  42232. var PushMaterial = /** @class */ (function (_super) {
  42233. __extends(PushMaterial, _super);
  42234. function PushMaterial(name, scene) {
  42235. var _this = _super.call(this, name, scene) || this;
  42236. _this._normalMatrix = new BABYLON.Matrix();
  42237. _this.storeEffectOnSubMeshes = true;
  42238. return _this;
  42239. }
  42240. PushMaterial.prototype.getEffect = function () {
  42241. return this._activeEffect;
  42242. };
  42243. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42244. if (!mesh) {
  42245. return false;
  42246. }
  42247. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42248. return true;
  42249. }
  42250. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42251. };
  42252. /**
  42253. * Binds the given world matrix to the active effect
  42254. *
  42255. * @param world the matrix to bind
  42256. */
  42257. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42258. this._activeEffect.setMatrix("world", world);
  42259. };
  42260. /**
  42261. * Binds the given normal matrix to the active effect
  42262. *
  42263. * @param normalMatrix the matrix to bind
  42264. */
  42265. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42266. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42267. };
  42268. PushMaterial.prototype.bind = function (world, mesh) {
  42269. if (!mesh) {
  42270. return;
  42271. }
  42272. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42273. };
  42274. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42275. if (effect === void 0) { effect = null; }
  42276. _super.prototype._afterBind.call(this, mesh);
  42277. this.getScene()._cachedEffect = effect;
  42278. };
  42279. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42280. if (visibility === void 0) { visibility = 1; }
  42281. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42282. };
  42283. return PushMaterial;
  42284. }(BABYLON.Material));
  42285. BABYLON.PushMaterial = PushMaterial;
  42286. })(BABYLON || (BABYLON = {}));
  42287. //# sourceMappingURL=babylon.pushMaterial.js.map
  42288. var BABYLON;
  42289. (function (BABYLON) {
  42290. /** @ignore */
  42291. var StandardMaterialDefines = /** @class */ (function (_super) {
  42292. __extends(StandardMaterialDefines, _super);
  42293. function StandardMaterialDefines() {
  42294. var _this = _super.call(this) || this;
  42295. _this.MAINUV1 = false;
  42296. _this.MAINUV2 = false;
  42297. _this.DIFFUSE = false;
  42298. _this.DIFFUSEDIRECTUV = 0;
  42299. _this.AMBIENT = false;
  42300. _this.AMBIENTDIRECTUV = 0;
  42301. _this.OPACITY = false;
  42302. _this.OPACITYDIRECTUV = 0;
  42303. _this.OPACITYRGB = false;
  42304. _this.REFLECTION = false;
  42305. _this.EMISSIVE = false;
  42306. _this.EMISSIVEDIRECTUV = 0;
  42307. _this.SPECULAR = false;
  42308. _this.SPECULARDIRECTUV = 0;
  42309. _this.BUMP = false;
  42310. _this.BUMPDIRECTUV = 0;
  42311. _this.PARALLAX = false;
  42312. _this.PARALLAXOCCLUSION = false;
  42313. _this.SPECULAROVERALPHA = false;
  42314. _this.CLIPPLANE = false;
  42315. _this.ALPHATEST = false;
  42316. _this.DEPTHPREPASS = false;
  42317. _this.ALPHAFROMDIFFUSE = false;
  42318. _this.POINTSIZE = false;
  42319. _this.FOG = false;
  42320. _this.SPECULARTERM = false;
  42321. _this.DIFFUSEFRESNEL = false;
  42322. _this.OPACITYFRESNEL = false;
  42323. _this.REFLECTIONFRESNEL = false;
  42324. _this.REFRACTIONFRESNEL = false;
  42325. _this.EMISSIVEFRESNEL = false;
  42326. _this.FRESNEL = false;
  42327. _this.NORMAL = false;
  42328. _this.UV1 = false;
  42329. _this.UV2 = false;
  42330. _this.VERTEXCOLOR = false;
  42331. _this.VERTEXALPHA = false;
  42332. _this.NUM_BONE_INFLUENCERS = 0;
  42333. _this.BonesPerMesh = 0;
  42334. _this.INSTANCES = false;
  42335. _this.GLOSSINESS = false;
  42336. _this.ROUGHNESS = false;
  42337. _this.EMISSIVEASILLUMINATION = false;
  42338. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42339. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42340. _this.LIGHTMAP = false;
  42341. _this.LIGHTMAPDIRECTUV = 0;
  42342. _this.OBJECTSPACE_NORMALMAP = false;
  42343. _this.USELIGHTMAPASSHADOWMAP = false;
  42344. _this.REFLECTIONMAP_3D = false;
  42345. _this.REFLECTIONMAP_SPHERICAL = false;
  42346. _this.REFLECTIONMAP_PLANAR = false;
  42347. _this.REFLECTIONMAP_CUBIC = false;
  42348. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42349. _this.REFLECTIONMAP_PROJECTION = false;
  42350. _this.REFLECTIONMAP_SKYBOX = false;
  42351. _this.REFLECTIONMAP_EXPLICIT = false;
  42352. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42353. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42354. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42355. _this.INVERTCUBICMAP = false;
  42356. _this.LOGARITHMICDEPTH = false;
  42357. _this.REFRACTION = false;
  42358. _this.REFRACTIONMAP_3D = false;
  42359. _this.REFLECTIONOVERALPHA = false;
  42360. _this.TWOSIDEDLIGHTING = false;
  42361. _this.SHADOWFLOAT = false;
  42362. _this.MORPHTARGETS = false;
  42363. _this.MORPHTARGETS_NORMAL = false;
  42364. _this.MORPHTARGETS_TANGENT = false;
  42365. _this.NUM_MORPH_INFLUENCERS = 0;
  42366. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42367. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42368. _this.IMAGEPROCESSING = false;
  42369. _this.VIGNETTE = false;
  42370. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42371. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42372. _this.TONEMAPPING = false;
  42373. _this.CONTRAST = false;
  42374. _this.COLORCURVES = false;
  42375. _this.COLORGRADING = false;
  42376. _this.COLORGRADING3D = false;
  42377. _this.SAMPLER3DGREENDEPTH = false;
  42378. _this.SAMPLER3DBGRMAP = false;
  42379. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42380. /**
  42381. * If the reflection texture on this material is in linear color space
  42382. * @ignore
  42383. */
  42384. _this.IS_REFLECTION_LINEAR = false;
  42385. /**
  42386. * If the refraction texture on this material is in linear color space
  42387. * @ignore
  42388. */
  42389. _this.IS_REFRACTION_LINEAR = false;
  42390. _this.EXPOSURE = false;
  42391. _this.rebuild();
  42392. return _this;
  42393. }
  42394. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42395. var modes = [
  42396. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42397. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42398. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42399. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42400. ];
  42401. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42402. var mode = modes_1[_i];
  42403. this[mode] = (mode === modeToEnable);
  42404. }
  42405. };
  42406. return StandardMaterialDefines;
  42407. }(BABYLON.MaterialDefines));
  42408. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42409. var StandardMaterial = /** @class */ (function (_super) {
  42410. __extends(StandardMaterial, _super);
  42411. function StandardMaterial(name, scene) {
  42412. var _this = _super.call(this, name, scene) || this;
  42413. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42414. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42415. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42416. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42417. _this.specularPower = 64;
  42418. _this._useAlphaFromDiffuseTexture = false;
  42419. _this._useEmissiveAsIllumination = false;
  42420. _this._linkEmissiveWithDiffuse = false;
  42421. _this._useSpecularOverAlpha = false;
  42422. _this._useReflectionOverAlpha = false;
  42423. _this._disableLighting = false;
  42424. _this._useObjectSpaceNormalMap = false;
  42425. _this._useParallax = false;
  42426. _this._useParallaxOcclusion = false;
  42427. _this.parallaxScaleBias = 0.05;
  42428. _this._roughness = 0;
  42429. _this.indexOfRefraction = 0.98;
  42430. _this.invertRefractionY = true;
  42431. _this._useLightmapAsShadowmap = false;
  42432. _this._useReflectionFresnelFromSpecular = false;
  42433. _this._useGlossinessFromSpecularMapAlpha = false;
  42434. _this._maxSimultaneousLights = 4;
  42435. /**
  42436. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42437. */
  42438. _this._invertNormalMapX = false;
  42439. /**
  42440. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42441. */
  42442. _this._invertNormalMapY = false;
  42443. /**
  42444. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42445. */
  42446. _this._twoSidedLighting = false;
  42447. _this._renderTargets = new BABYLON.SmartArray(16);
  42448. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42449. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42450. // Setup the default processing configuration to the scene.
  42451. _this._attachImageProcessingConfiguration(null);
  42452. _this.getRenderTargetTextures = function () {
  42453. _this._renderTargets.reset();
  42454. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42455. _this._renderTargets.push(_this._reflectionTexture);
  42456. }
  42457. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42458. _this._renderTargets.push(_this._refractionTexture);
  42459. }
  42460. return _this._renderTargets;
  42461. };
  42462. return _this;
  42463. }
  42464. ;
  42465. ;
  42466. ;
  42467. ;
  42468. ;
  42469. ;
  42470. ;
  42471. ;
  42472. ;
  42473. ;
  42474. ;
  42475. ;
  42476. ;
  42477. ;
  42478. ;
  42479. ;
  42480. ;
  42481. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42482. /**
  42483. * Gets the image processing configuration used either in this material.
  42484. */
  42485. get: function () {
  42486. return this._imageProcessingConfiguration;
  42487. },
  42488. /**
  42489. * Sets the Default image processing configuration used either in the this material.
  42490. *
  42491. * If sets to null, the scene one is in use.
  42492. */
  42493. set: function (value) {
  42494. this._attachImageProcessingConfiguration(value);
  42495. // Ensure the effect will be rebuilt.
  42496. this._markAllSubMeshesAsTexturesDirty();
  42497. },
  42498. enumerable: true,
  42499. configurable: true
  42500. });
  42501. /**
  42502. * Attaches a new image processing configuration to the Standard Material.
  42503. * @param configuration
  42504. */
  42505. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42506. var _this = this;
  42507. if (configuration === this._imageProcessingConfiguration) {
  42508. return;
  42509. }
  42510. // Detaches observer.
  42511. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42512. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42513. }
  42514. // Pick the scene configuration if needed.
  42515. if (!configuration) {
  42516. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42517. }
  42518. else {
  42519. this._imageProcessingConfiguration = configuration;
  42520. }
  42521. // Attaches observer.
  42522. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42523. _this._markAllSubMeshesAsImageProcessingDirty();
  42524. });
  42525. };
  42526. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42527. /**
  42528. * Gets wether the color curves effect is enabled.
  42529. */
  42530. get: function () {
  42531. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42532. },
  42533. /**
  42534. * Sets wether the color curves effect is enabled.
  42535. */
  42536. set: function (value) {
  42537. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42538. },
  42539. enumerable: true,
  42540. configurable: true
  42541. });
  42542. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42543. /**
  42544. * Gets wether the color grading effect is enabled.
  42545. */
  42546. get: function () {
  42547. return this.imageProcessingConfiguration.colorGradingEnabled;
  42548. },
  42549. /**
  42550. * Gets wether the color grading effect is enabled.
  42551. */
  42552. set: function (value) {
  42553. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42554. },
  42555. enumerable: true,
  42556. configurable: true
  42557. });
  42558. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42559. /**
  42560. * Gets wether tonemapping is enabled or not.
  42561. */
  42562. get: function () {
  42563. return this._imageProcessingConfiguration.toneMappingEnabled;
  42564. },
  42565. /**
  42566. * Sets wether tonemapping is enabled or not
  42567. */
  42568. set: function (value) {
  42569. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42570. },
  42571. enumerable: true,
  42572. configurable: true
  42573. });
  42574. ;
  42575. ;
  42576. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42577. /**
  42578. * The camera exposure used on this material.
  42579. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42580. * This corresponds to a photographic exposure.
  42581. */
  42582. get: function () {
  42583. return this._imageProcessingConfiguration.exposure;
  42584. },
  42585. /**
  42586. * The camera exposure used on this material.
  42587. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42588. * This corresponds to a photographic exposure.
  42589. */
  42590. set: function (value) {
  42591. this._imageProcessingConfiguration.exposure = value;
  42592. },
  42593. enumerable: true,
  42594. configurable: true
  42595. });
  42596. ;
  42597. ;
  42598. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42599. /**
  42600. * Gets The camera contrast used on this material.
  42601. */
  42602. get: function () {
  42603. return this._imageProcessingConfiguration.contrast;
  42604. },
  42605. /**
  42606. * Sets The camera contrast used on this material.
  42607. */
  42608. set: function (value) {
  42609. this._imageProcessingConfiguration.contrast = value;
  42610. },
  42611. enumerable: true,
  42612. configurable: true
  42613. });
  42614. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42615. /**
  42616. * Gets the Color Grading 2D Lookup Texture.
  42617. */
  42618. get: function () {
  42619. return this._imageProcessingConfiguration.colorGradingTexture;
  42620. },
  42621. /**
  42622. * Sets the Color Grading 2D Lookup Texture.
  42623. */
  42624. set: function (value) {
  42625. this._imageProcessingConfiguration.colorGradingTexture = value;
  42626. },
  42627. enumerable: true,
  42628. configurable: true
  42629. });
  42630. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42631. /**
  42632. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42633. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42634. * 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;
  42635. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42636. */
  42637. get: function () {
  42638. return this._imageProcessingConfiguration.colorCurves;
  42639. },
  42640. /**
  42641. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42642. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42643. * 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;
  42644. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42645. */
  42646. set: function (value) {
  42647. this._imageProcessingConfiguration.colorCurves = value;
  42648. },
  42649. enumerable: true,
  42650. configurable: true
  42651. });
  42652. StandardMaterial.prototype.getClassName = function () {
  42653. return "StandardMaterial";
  42654. };
  42655. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42656. get: function () {
  42657. return this._useLogarithmicDepth;
  42658. },
  42659. set: function (value) {
  42660. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42661. this._markAllSubMeshesAsMiscDirty();
  42662. },
  42663. enumerable: true,
  42664. configurable: true
  42665. });
  42666. StandardMaterial.prototype.needAlphaBlending = function () {
  42667. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42668. };
  42669. StandardMaterial.prototype.needAlphaTesting = function () {
  42670. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42671. };
  42672. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42673. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42674. };
  42675. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42676. return this._diffuseTexture;
  42677. };
  42678. /**
  42679. * Child classes can use it to update shaders
  42680. */
  42681. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42682. if (useInstances === void 0) { useInstances = false; }
  42683. if (subMesh.effect && this.isFrozen) {
  42684. if (this._wasPreviouslyReady && subMesh.effect) {
  42685. return true;
  42686. }
  42687. }
  42688. if (!subMesh._materialDefines) {
  42689. subMesh._materialDefines = new StandardMaterialDefines();
  42690. }
  42691. var scene = this.getScene();
  42692. var defines = subMesh._materialDefines;
  42693. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42694. if (defines._renderId === scene.getRenderId()) {
  42695. return true;
  42696. }
  42697. }
  42698. var engine = scene.getEngine();
  42699. // Lights
  42700. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42701. // Textures
  42702. if (defines._areTexturesDirty) {
  42703. defines._needUVs = false;
  42704. defines.MAINUV1 = false;
  42705. defines.MAINUV2 = false;
  42706. if (scene.texturesEnabled) {
  42707. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42708. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42709. return false;
  42710. }
  42711. else {
  42712. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42713. }
  42714. }
  42715. else {
  42716. defines.DIFFUSE = false;
  42717. }
  42718. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42719. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42720. return false;
  42721. }
  42722. else {
  42723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42724. }
  42725. }
  42726. else {
  42727. defines.AMBIENT = false;
  42728. }
  42729. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42730. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42731. return false;
  42732. }
  42733. else {
  42734. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42735. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42736. }
  42737. }
  42738. else {
  42739. defines.OPACITY = false;
  42740. }
  42741. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42742. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42743. return false;
  42744. }
  42745. else {
  42746. defines._needNormals = true;
  42747. defines.REFLECTION = true;
  42748. defines.ROUGHNESS = (this._roughness > 0);
  42749. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42750. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42751. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42752. switch (this._reflectionTexture.coordinatesMode) {
  42753. case BABYLON.Texture.CUBIC_MODE:
  42754. case BABYLON.Texture.INVCUBIC_MODE:
  42755. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42756. break;
  42757. case BABYLON.Texture.EXPLICIT_MODE:
  42758. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42759. break;
  42760. case BABYLON.Texture.PLANAR_MODE:
  42761. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42762. break;
  42763. case BABYLON.Texture.PROJECTION_MODE:
  42764. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42765. break;
  42766. case BABYLON.Texture.SKYBOX_MODE:
  42767. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42768. break;
  42769. case BABYLON.Texture.SPHERICAL_MODE:
  42770. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42771. break;
  42772. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42773. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42774. break;
  42775. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42776. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42777. break;
  42778. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42779. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42780. break;
  42781. }
  42782. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42783. }
  42784. }
  42785. else {
  42786. defines.REFLECTION = false;
  42787. }
  42788. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42789. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42790. return false;
  42791. }
  42792. else {
  42793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42794. }
  42795. }
  42796. else {
  42797. defines.EMISSIVE = false;
  42798. }
  42799. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42800. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42801. return false;
  42802. }
  42803. else {
  42804. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42805. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42806. }
  42807. }
  42808. else {
  42809. defines.LIGHTMAP = false;
  42810. }
  42811. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42812. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42813. return false;
  42814. }
  42815. else {
  42816. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42817. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42818. }
  42819. }
  42820. else {
  42821. defines.SPECULAR = false;
  42822. }
  42823. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42824. // Bump texure can not be not blocking.
  42825. if (!this._bumpTexture.isReady()) {
  42826. return false;
  42827. }
  42828. else {
  42829. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42830. defines.PARALLAX = this._useParallax;
  42831. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42832. }
  42833. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42834. }
  42835. else {
  42836. defines.BUMP = false;
  42837. }
  42838. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42839. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42840. return false;
  42841. }
  42842. else {
  42843. defines._needUVs = true;
  42844. defines.REFRACTION = true;
  42845. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42846. }
  42847. }
  42848. else {
  42849. defines.REFRACTION = false;
  42850. }
  42851. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42852. }
  42853. else {
  42854. defines.DIFFUSE = false;
  42855. defines.AMBIENT = false;
  42856. defines.OPACITY = false;
  42857. defines.REFLECTION = false;
  42858. defines.EMISSIVE = false;
  42859. defines.LIGHTMAP = false;
  42860. defines.BUMP = false;
  42861. defines.REFRACTION = false;
  42862. }
  42863. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42864. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42865. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42866. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42867. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42868. }
  42869. if (defines._areImageProcessingDirty) {
  42870. if (!this._imageProcessingConfiguration.isReady()) {
  42871. return false;
  42872. }
  42873. this._imageProcessingConfiguration.prepareDefines(defines);
  42874. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42875. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42876. }
  42877. if (defines._areFresnelDirty) {
  42878. if (StandardMaterial.FresnelEnabled) {
  42879. // Fresnel
  42880. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42881. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42882. this._reflectionFresnelParameters) {
  42883. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42884. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42885. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42886. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42887. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42888. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42889. defines._needNormals = true;
  42890. defines.FRESNEL = true;
  42891. }
  42892. }
  42893. else {
  42894. defines.FRESNEL = false;
  42895. }
  42896. }
  42897. // Misc.
  42898. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42899. // Attribs
  42900. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42901. // Values that need to be evaluated on every frame
  42902. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42903. // Get correct effect
  42904. if (defines.isDirty) {
  42905. defines.markAsProcessed();
  42906. scene.resetCachedMaterial();
  42907. // Fallbacks
  42908. var fallbacks = new BABYLON.EffectFallbacks();
  42909. if (defines.REFLECTION) {
  42910. fallbacks.addFallback(0, "REFLECTION");
  42911. }
  42912. if (defines.SPECULAR) {
  42913. fallbacks.addFallback(0, "SPECULAR");
  42914. }
  42915. if (defines.BUMP) {
  42916. fallbacks.addFallback(0, "BUMP");
  42917. }
  42918. if (defines.PARALLAX) {
  42919. fallbacks.addFallback(1, "PARALLAX");
  42920. }
  42921. if (defines.PARALLAXOCCLUSION) {
  42922. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42923. }
  42924. if (defines.SPECULAROVERALPHA) {
  42925. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42926. }
  42927. if (defines.FOG) {
  42928. fallbacks.addFallback(1, "FOG");
  42929. }
  42930. if (defines.POINTSIZE) {
  42931. fallbacks.addFallback(0, "POINTSIZE");
  42932. }
  42933. if (defines.LOGARITHMICDEPTH) {
  42934. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42935. }
  42936. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42937. if (defines.SPECULARTERM) {
  42938. fallbacks.addFallback(0, "SPECULARTERM");
  42939. }
  42940. if (defines.DIFFUSEFRESNEL) {
  42941. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42942. }
  42943. if (defines.OPACITYFRESNEL) {
  42944. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42945. }
  42946. if (defines.REFLECTIONFRESNEL) {
  42947. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42948. }
  42949. if (defines.EMISSIVEFRESNEL) {
  42950. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42951. }
  42952. if (defines.FRESNEL) {
  42953. fallbacks.addFallback(4, "FRESNEL");
  42954. }
  42955. //Attributes
  42956. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42957. if (defines.NORMAL) {
  42958. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42959. }
  42960. if (defines.UV1) {
  42961. attribs.push(BABYLON.VertexBuffer.UVKind);
  42962. }
  42963. if (defines.UV2) {
  42964. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42965. }
  42966. if (defines.VERTEXCOLOR) {
  42967. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42968. }
  42969. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42970. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42971. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42972. var shaderName = "default";
  42973. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42974. "vFogInfos", "vFogColor", "pointSize",
  42975. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42976. "mBones",
  42977. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42978. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42979. "vReflectionPosition", "vReflectionSize",
  42980. "logarithmicDepthConstant", "vTangentSpaceParams"
  42981. ];
  42982. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42983. var uniformBuffers = ["Material", "Scene"];
  42984. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42985. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42986. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42987. uniformsNames: uniforms,
  42988. uniformBuffersNames: uniformBuffers,
  42989. samplers: samplers,
  42990. defines: defines,
  42991. maxSimultaneousLights: this._maxSimultaneousLights
  42992. });
  42993. if (this.customShaderNameResolve) {
  42994. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42995. }
  42996. var join = defines.toString();
  42997. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42998. attributes: attribs,
  42999. uniformsNames: uniforms,
  43000. uniformBuffersNames: uniformBuffers,
  43001. samplers: samplers,
  43002. defines: join,
  43003. fallbacks: fallbacks,
  43004. onCompiled: this.onCompiled,
  43005. onError: this.onError,
  43006. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43007. }, engine), defines);
  43008. this.buildUniformLayout();
  43009. }
  43010. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43011. return false;
  43012. }
  43013. defines._renderId = scene.getRenderId();
  43014. this._wasPreviouslyReady = true;
  43015. return true;
  43016. };
  43017. StandardMaterial.prototype.buildUniformLayout = function () {
  43018. // Order is important !
  43019. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43020. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43021. this._uniformBuffer.addUniform("opacityParts", 4);
  43022. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43023. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43024. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43025. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43026. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43027. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43028. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43029. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43030. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43031. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43032. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43033. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43034. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43035. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43036. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43037. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43038. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43039. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43040. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43041. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43042. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43043. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43044. this._uniformBuffer.addUniform("specularMatrix", 16);
  43045. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43046. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43047. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43048. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43049. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43050. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43051. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43052. this._uniformBuffer.addUniform("pointSize", 1);
  43053. this._uniformBuffer.create();
  43054. };
  43055. StandardMaterial.prototype.unbind = function () {
  43056. if (this._activeEffect) {
  43057. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43058. this._activeEffect.setTexture("reflection2DSampler", null);
  43059. }
  43060. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43061. this._activeEffect.setTexture("refraction2DSampler", null);
  43062. }
  43063. }
  43064. _super.prototype.unbind.call(this);
  43065. };
  43066. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43067. var scene = this.getScene();
  43068. var defines = subMesh._materialDefines;
  43069. if (!defines) {
  43070. return;
  43071. }
  43072. var effect = subMesh.effect;
  43073. if (!effect) {
  43074. return;
  43075. }
  43076. this._activeEffect = effect;
  43077. // Matrices
  43078. this.bindOnlyWorldMatrix(world);
  43079. // Normal Matrix
  43080. if (defines.OBJECTSPACE_NORMALMAP) {
  43081. world.toNormalMatrix(this._normalMatrix);
  43082. this.bindOnlyNormalMatrix(this._normalMatrix);
  43083. }
  43084. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43085. // Bones
  43086. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43087. if (mustRebind) {
  43088. this._uniformBuffer.bindToEffect(effect, "Material");
  43089. this.bindViewProjection(effect);
  43090. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43091. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43092. // Fresnel
  43093. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43094. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43095. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43096. }
  43097. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43098. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43099. }
  43100. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43101. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43102. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43103. }
  43104. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43105. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43106. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43107. }
  43108. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43109. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43110. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43111. }
  43112. }
  43113. // Textures
  43114. if (scene.texturesEnabled) {
  43115. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43116. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43117. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43118. }
  43119. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43120. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43121. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43122. }
  43123. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43124. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43125. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43126. }
  43127. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43128. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43129. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43130. if (this._reflectionTexture.boundingBoxSize) {
  43131. var cubeTexture = this._reflectionTexture;
  43132. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43133. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43134. }
  43135. }
  43136. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43137. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43138. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43139. }
  43140. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43141. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43142. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43143. }
  43144. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43145. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43146. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43147. }
  43148. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43149. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43150. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43151. if (scene._mirroredCameraPosition) {
  43152. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43153. }
  43154. else {
  43155. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43156. }
  43157. }
  43158. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43159. var depth = 1.0;
  43160. if (!this._refractionTexture.isCube) {
  43161. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43162. if (this._refractionTexture.depth) {
  43163. depth = this._refractionTexture.depth;
  43164. }
  43165. }
  43166. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43167. }
  43168. }
  43169. // Point size
  43170. if (this.pointsCloud) {
  43171. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43172. }
  43173. if (defines.SPECULARTERM) {
  43174. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43175. }
  43176. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43177. // Diffuse
  43178. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43179. }
  43180. // Textures
  43181. if (scene.texturesEnabled) {
  43182. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43183. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43184. }
  43185. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43186. effect.setTexture("ambientSampler", this._ambientTexture);
  43187. }
  43188. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43189. effect.setTexture("opacitySampler", this._opacityTexture);
  43190. }
  43191. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43192. if (this._reflectionTexture.isCube) {
  43193. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43194. }
  43195. else {
  43196. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43197. }
  43198. }
  43199. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43200. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43201. }
  43202. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43203. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43204. }
  43205. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43206. effect.setTexture("specularSampler", this._specularTexture);
  43207. }
  43208. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43209. effect.setTexture("bumpSampler", this._bumpTexture);
  43210. }
  43211. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43212. var depth = 1.0;
  43213. if (this._refractionTexture.isCube) {
  43214. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43215. }
  43216. else {
  43217. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43218. }
  43219. }
  43220. }
  43221. // Clip plane
  43222. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43223. // Colors
  43224. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43225. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43226. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43227. }
  43228. if (mustRebind || !this.isFrozen) {
  43229. // Lights
  43230. if (scene.lightsEnabled && !this._disableLighting) {
  43231. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43232. }
  43233. // View
  43234. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43235. this.bindView(effect);
  43236. }
  43237. // Fog
  43238. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43239. // Morph targets
  43240. if (defines.NUM_MORPH_INFLUENCERS) {
  43241. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43242. }
  43243. // Log. depth
  43244. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43245. // image processing
  43246. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43247. this._imageProcessingConfiguration.bind(this._activeEffect);
  43248. }
  43249. }
  43250. this._uniformBuffer.update();
  43251. this._afterBind(mesh, this._activeEffect);
  43252. };
  43253. StandardMaterial.prototype.getAnimatables = function () {
  43254. var results = [];
  43255. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43256. results.push(this._diffuseTexture);
  43257. }
  43258. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43259. results.push(this._ambientTexture);
  43260. }
  43261. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43262. results.push(this._opacityTexture);
  43263. }
  43264. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43265. results.push(this._reflectionTexture);
  43266. }
  43267. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43268. results.push(this._emissiveTexture);
  43269. }
  43270. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43271. results.push(this._specularTexture);
  43272. }
  43273. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43274. results.push(this._bumpTexture);
  43275. }
  43276. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43277. results.push(this._lightmapTexture);
  43278. }
  43279. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43280. results.push(this._refractionTexture);
  43281. }
  43282. return results;
  43283. };
  43284. StandardMaterial.prototype.getActiveTextures = function () {
  43285. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43286. if (this._diffuseTexture) {
  43287. activeTextures.push(this._diffuseTexture);
  43288. }
  43289. if (this._ambientTexture) {
  43290. activeTextures.push(this._ambientTexture);
  43291. }
  43292. if (this._opacityTexture) {
  43293. activeTextures.push(this._opacityTexture);
  43294. }
  43295. if (this._reflectionTexture) {
  43296. activeTextures.push(this._reflectionTexture);
  43297. }
  43298. if (this._emissiveTexture) {
  43299. activeTextures.push(this._emissiveTexture);
  43300. }
  43301. if (this._specularTexture) {
  43302. activeTextures.push(this._specularTexture);
  43303. }
  43304. if (this._bumpTexture) {
  43305. activeTextures.push(this._bumpTexture);
  43306. }
  43307. if (this._lightmapTexture) {
  43308. activeTextures.push(this._lightmapTexture);
  43309. }
  43310. if (this._refractionTexture) {
  43311. activeTextures.push(this._refractionTexture);
  43312. }
  43313. return activeTextures;
  43314. };
  43315. StandardMaterial.prototype.hasTexture = function (texture) {
  43316. if (_super.prototype.hasTexture.call(this, texture)) {
  43317. return true;
  43318. }
  43319. if (this._diffuseTexture === texture) {
  43320. return true;
  43321. }
  43322. if (this._ambientTexture === texture) {
  43323. return true;
  43324. }
  43325. if (this._opacityTexture === texture) {
  43326. return true;
  43327. }
  43328. if (this._reflectionTexture === texture) {
  43329. return true;
  43330. }
  43331. if (this._emissiveTexture === texture) {
  43332. return true;
  43333. }
  43334. if (this._specularTexture === texture) {
  43335. return true;
  43336. }
  43337. if (this._bumpTexture === texture) {
  43338. return true;
  43339. }
  43340. if (this._lightmapTexture === texture) {
  43341. return true;
  43342. }
  43343. if (this._refractionTexture === texture) {
  43344. return true;
  43345. }
  43346. return false;
  43347. };
  43348. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43349. if (forceDisposeTextures) {
  43350. if (this._diffuseTexture) {
  43351. this._diffuseTexture.dispose();
  43352. }
  43353. if (this._ambientTexture) {
  43354. this._ambientTexture.dispose();
  43355. }
  43356. if (this._opacityTexture) {
  43357. this._opacityTexture.dispose();
  43358. }
  43359. if (this._reflectionTexture) {
  43360. this._reflectionTexture.dispose();
  43361. }
  43362. if (this._emissiveTexture) {
  43363. this._emissiveTexture.dispose();
  43364. }
  43365. if (this._specularTexture) {
  43366. this._specularTexture.dispose();
  43367. }
  43368. if (this._bumpTexture) {
  43369. this._bumpTexture.dispose();
  43370. }
  43371. if (this._lightmapTexture) {
  43372. this._lightmapTexture.dispose();
  43373. }
  43374. if (this._refractionTexture) {
  43375. this._refractionTexture.dispose();
  43376. }
  43377. }
  43378. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43379. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43380. }
  43381. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43382. };
  43383. StandardMaterial.prototype.clone = function (name) {
  43384. var _this = this;
  43385. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43386. result.name = name;
  43387. result.id = name;
  43388. return result;
  43389. };
  43390. StandardMaterial.prototype.serialize = function () {
  43391. return BABYLON.SerializationHelper.Serialize(this);
  43392. };
  43393. // Statics
  43394. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43395. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43396. };
  43397. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43398. get: function () {
  43399. return StandardMaterial._DiffuseTextureEnabled;
  43400. },
  43401. set: function (value) {
  43402. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43403. return;
  43404. }
  43405. StandardMaterial._DiffuseTextureEnabled = value;
  43406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43407. },
  43408. enumerable: true,
  43409. configurable: true
  43410. });
  43411. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43412. get: function () {
  43413. return StandardMaterial._AmbientTextureEnabled;
  43414. },
  43415. set: function (value) {
  43416. if (StandardMaterial._AmbientTextureEnabled === value) {
  43417. return;
  43418. }
  43419. StandardMaterial._AmbientTextureEnabled = value;
  43420. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43421. },
  43422. enumerable: true,
  43423. configurable: true
  43424. });
  43425. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43426. get: function () {
  43427. return StandardMaterial._OpacityTextureEnabled;
  43428. },
  43429. set: function (value) {
  43430. if (StandardMaterial._OpacityTextureEnabled === value) {
  43431. return;
  43432. }
  43433. StandardMaterial._OpacityTextureEnabled = value;
  43434. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43435. },
  43436. enumerable: true,
  43437. configurable: true
  43438. });
  43439. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43440. get: function () {
  43441. return StandardMaterial._ReflectionTextureEnabled;
  43442. },
  43443. set: function (value) {
  43444. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43445. return;
  43446. }
  43447. StandardMaterial._ReflectionTextureEnabled = value;
  43448. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43449. },
  43450. enumerable: true,
  43451. configurable: true
  43452. });
  43453. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43454. get: function () {
  43455. return StandardMaterial._EmissiveTextureEnabled;
  43456. },
  43457. set: function (value) {
  43458. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43459. return;
  43460. }
  43461. StandardMaterial._EmissiveTextureEnabled = value;
  43462. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43463. },
  43464. enumerable: true,
  43465. configurable: true
  43466. });
  43467. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43468. get: function () {
  43469. return StandardMaterial._SpecularTextureEnabled;
  43470. },
  43471. set: function (value) {
  43472. if (StandardMaterial._SpecularTextureEnabled === value) {
  43473. return;
  43474. }
  43475. StandardMaterial._SpecularTextureEnabled = value;
  43476. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43477. },
  43478. enumerable: true,
  43479. configurable: true
  43480. });
  43481. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43482. get: function () {
  43483. return StandardMaterial._BumpTextureEnabled;
  43484. },
  43485. set: function (value) {
  43486. if (StandardMaterial._BumpTextureEnabled === value) {
  43487. return;
  43488. }
  43489. StandardMaterial._BumpTextureEnabled = value;
  43490. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43491. },
  43492. enumerable: true,
  43493. configurable: true
  43494. });
  43495. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43496. get: function () {
  43497. return StandardMaterial._LightmapTextureEnabled;
  43498. },
  43499. set: function (value) {
  43500. if (StandardMaterial._LightmapTextureEnabled === value) {
  43501. return;
  43502. }
  43503. StandardMaterial._LightmapTextureEnabled = value;
  43504. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43510. get: function () {
  43511. return StandardMaterial._RefractionTextureEnabled;
  43512. },
  43513. set: function (value) {
  43514. if (StandardMaterial._RefractionTextureEnabled === value) {
  43515. return;
  43516. }
  43517. StandardMaterial._RefractionTextureEnabled = value;
  43518. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43519. },
  43520. enumerable: true,
  43521. configurable: true
  43522. });
  43523. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43524. get: function () {
  43525. return StandardMaterial._ColorGradingTextureEnabled;
  43526. },
  43527. set: function (value) {
  43528. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43529. return;
  43530. }
  43531. StandardMaterial._ColorGradingTextureEnabled = value;
  43532. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43533. },
  43534. enumerable: true,
  43535. configurable: true
  43536. });
  43537. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43538. get: function () {
  43539. return StandardMaterial._FresnelEnabled;
  43540. },
  43541. set: function (value) {
  43542. if (StandardMaterial._FresnelEnabled === value) {
  43543. return;
  43544. }
  43545. StandardMaterial._FresnelEnabled = value;
  43546. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43547. },
  43548. enumerable: true,
  43549. configurable: true
  43550. });
  43551. // Flags used to enable or disable a type of texture for all Standard Materials
  43552. StandardMaterial._DiffuseTextureEnabled = true;
  43553. StandardMaterial._AmbientTextureEnabled = true;
  43554. StandardMaterial._OpacityTextureEnabled = true;
  43555. StandardMaterial._ReflectionTextureEnabled = true;
  43556. StandardMaterial._EmissiveTextureEnabled = true;
  43557. StandardMaterial._SpecularTextureEnabled = true;
  43558. StandardMaterial._BumpTextureEnabled = true;
  43559. StandardMaterial._LightmapTextureEnabled = true;
  43560. StandardMaterial._RefractionTextureEnabled = true;
  43561. StandardMaterial._ColorGradingTextureEnabled = true;
  43562. StandardMaterial._FresnelEnabled = true;
  43563. __decorate([
  43564. BABYLON.serializeAsTexture("diffuseTexture")
  43565. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43566. __decorate([
  43567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43568. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43569. __decorate([
  43570. BABYLON.serializeAsTexture("ambientTexture")
  43571. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43572. __decorate([
  43573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43574. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43575. __decorate([
  43576. BABYLON.serializeAsTexture("opacityTexture")
  43577. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43578. __decorate([
  43579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43580. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43581. __decorate([
  43582. BABYLON.serializeAsTexture("reflectionTexture")
  43583. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43584. __decorate([
  43585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43586. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43587. __decorate([
  43588. BABYLON.serializeAsTexture("emissiveTexture")
  43589. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43590. __decorate([
  43591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43592. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43593. __decorate([
  43594. BABYLON.serializeAsTexture("specularTexture")
  43595. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43596. __decorate([
  43597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43598. ], StandardMaterial.prototype, "specularTexture", void 0);
  43599. __decorate([
  43600. BABYLON.serializeAsTexture("bumpTexture")
  43601. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43602. __decorate([
  43603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43604. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43605. __decorate([
  43606. BABYLON.serializeAsTexture("lightmapTexture")
  43607. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43608. __decorate([
  43609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43610. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43611. __decorate([
  43612. BABYLON.serializeAsTexture("refractionTexture")
  43613. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43614. __decorate([
  43615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43616. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43617. __decorate([
  43618. BABYLON.serializeAsColor3("ambient")
  43619. ], StandardMaterial.prototype, "ambientColor", void 0);
  43620. __decorate([
  43621. BABYLON.serializeAsColor3("diffuse")
  43622. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43623. __decorate([
  43624. BABYLON.serializeAsColor3("specular")
  43625. ], StandardMaterial.prototype, "specularColor", void 0);
  43626. __decorate([
  43627. BABYLON.serializeAsColor3("emissive")
  43628. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43629. __decorate([
  43630. BABYLON.serialize()
  43631. ], StandardMaterial.prototype, "specularPower", void 0);
  43632. __decorate([
  43633. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43634. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43635. __decorate([
  43636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43637. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43638. __decorate([
  43639. BABYLON.serialize("useEmissiveAsIllumination")
  43640. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43641. __decorate([
  43642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43643. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43644. __decorate([
  43645. BABYLON.serialize("linkEmissiveWithDiffuse")
  43646. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43647. __decorate([
  43648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43649. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43650. __decorate([
  43651. BABYLON.serialize("useSpecularOverAlpha")
  43652. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43653. __decorate([
  43654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43655. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43656. __decorate([
  43657. BABYLON.serialize("useReflectionOverAlpha")
  43658. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43659. __decorate([
  43660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43661. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43662. __decorate([
  43663. BABYLON.serialize("disableLighting")
  43664. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43665. __decorate([
  43666. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43667. ], StandardMaterial.prototype, "disableLighting", void 0);
  43668. __decorate([
  43669. BABYLON.serialize("useObjectSpaceNormalMap")
  43670. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43671. __decorate([
  43672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43673. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43674. __decorate([
  43675. BABYLON.serialize("useParallax")
  43676. ], StandardMaterial.prototype, "_useParallax", void 0);
  43677. __decorate([
  43678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43679. ], StandardMaterial.prototype, "useParallax", void 0);
  43680. __decorate([
  43681. BABYLON.serialize("useParallaxOcclusion")
  43682. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43683. __decorate([
  43684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43685. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43686. __decorate([
  43687. BABYLON.serialize()
  43688. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43689. __decorate([
  43690. BABYLON.serialize("roughness")
  43691. ], StandardMaterial.prototype, "_roughness", void 0);
  43692. __decorate([
  43693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43694. ], StandardMaterial.prototype, "roughness", void 0);
  43695. __decorate([
  43696. BABYLON.serialize()
  43697. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43698. __decorate([
  43699. BABYLON.serialize()
  43700. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43701. __decorate([
  43702. BABYLON.serialize("useLightmapAsShadowmap")
  43703. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43704. __decorate([
  43705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43706. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43707. __decorate([
  43708. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43709. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43710. __decorate([
  43711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43712. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43713. __decorate([
  43714. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43715. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43716. __decorate([
  43717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43718. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43719. __decorate([
  43720. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43721. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43722. __decorate([
  43723. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43724. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43725. __decorate([
  43726. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43727. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43728. __decorate([
  43729. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43730. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43731. __decorate([
  43732. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43733. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43734. __decorate([
  43735. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43736. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43737. __decorate([
  43738. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43739. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43740. __decorate([
  43741. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43742. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43743. __decorate([
  43744. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43745. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43746. __decorate([
  43747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43748. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43749. __decorate([
  43750. BABYLON.serialize("maxSimultaneousLights")
  43751. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43752. __decorate([
  43753. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43754. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43755. __decorate([
  43756. BABYLON.serialize("invertNormalMapX")
  43757. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43758. __decorate([
  43759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43760. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43761. __decorate([
  43762. BABYLON.serialize("invertNormalMapY")
  43763. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43764. __decorate([
  43765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43766. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43767. __decorate([
  43768. BABYLON.serialize("twoSidedLighting")
  43769. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43770. __decorate([
  43771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43772. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43773. __decorate([
  43774. BABYLON.serialize()
  43775. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43776. return StandardMaterial;
  43777. }(BABYLON.PushMaterial));
  43778. BABYLON.StandardMaterial = StandardMaterial;
  43779. })(BABYLON || (BABYLON = {}));
  43780. //# sourceMappingURL=babylon.standardMaterial.js.map
  43781. var BABYLON;
  43782. (function (BABYLON) {
  43783. /**
  43784. * Manages the defines for the PBR Material.
  43785. * @ignoreChildren
  43786. */
  43787. var PBRMaterialDefines = /** @class */ (function (_super) {
  43788. __extends(PBRMaterialDefines, _super);
  43789. /**
  43790. * Initializes the PBR Material defines.
  43791. */
  43792. function PBRMaterialDefines() {
  43793. var _this = _super.call(this) || this;
  43794. _this.PBR = true;
  43795. _this.MAINUV1 = false;
  43796. _this.MAINUV2 = false;
  43797. _this.UV1 = false;
  43798. _this.UV2 = false;
  43799. _this.ALBEDO = false;
  43800. _this.ALBEDODIRECTUV = 0;
  43801. _this.VERTEXCOLOR = false;
  43802. _this.AMBIENT = false;
  43803. _this.AMBIENTDIRECTUV = 0;
  43804. _this.AMBIENTINGRAYSCALE = false;
  43805. _this.OPACITY = false;
  43806. _this.VERTEXALPHA = false;
  43807. _this.OPACITYDIRECTUV = 0;
  43808. _this.OPACITYRGB = false;
  43809. _this.ALPHATEST = false;
  43810. _this.DEPTHPREPASS = false;
  43811. _this.ALPHABLEND = false;
  43812. _this.ALPHAFROMALBEDO = false;
  43813. _this.ALPHATESTVALUE = "0.5";
  43814. _this.SPECULAROVERALPHA = false;
  43815. _this.RADIANCEOVERALPHA = false;
  43816. _this.ALPHAFRESNEL = false;
  43817. _this.LINEARALPHAFRESNEL = false;
  43818. _this.PREMULTIPLYALPHA = false;
  43819. _this.EMISSIVE = false;
  43820. _this.EMISSIVEDIRECTUV = 0;
  43821. _this.REFLECTIVITY = false;
  43822. _this.REFLECTIVITYDIRECTUV = 0;
  43823. _this.SPECULARTERM = false;
  43824. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43825. _this.MICROSURFACEAUTOMATIC = false;
  43826. _this.LODBASEDMICROSFURACE = false;
  43827. _this.MICROSURFACEMAP = false;
  43828. _this.MICROSURFACEMAPDIRECTUV = 0;
  43829. _this.METALLICWORKFLOW = false;
  43830. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43831. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43832. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43833. _this.AOSTOREINMETALMAPRED = false;
  43834. _this.ENVIRONMENTBRDF = false;
  43835. _this.NORMAL = false;
  43836. _this.TANGENT = false;
  43837. _this.BUMP = false;
  43838. _this.BUMPDIRECTUV = 0;
  43839. _this.OBJECTSPACE_NORMALMAP = false;
  43840. _this.PARALLAX = false;
  43841. _this.PARALLAXOCCLUSION = false;
  43842. _this.NORMALXYSCALE = true;
  43843. _this.LIGHTMAP = false;
  43844. _this.LIGHTMAPDIRECTUV = 0;
  43845. _this.USELIGHTMAPASSHADOWMAP = false;
  43846. _this.GAMMALIGHTMAP = false;
  43847. _this.REFLECTION = false;
  43848. _this.REFLECTIONMAP_3D = false;
  43849. _this.REFLECTIONMAP_SPHERICAL = false;
  43850. _this.REFLECTIONMAP_PLANAR = false;
  43851. _this.REFLECTIONMAP_CUBIC = false;
  43852. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43853. _this.REFLECTIONMAP_PROJECTION = false;
  43854. _this.REFLECTIONMAP_SKYBOX = false;
  43855. _this.REFLECTIONMAP_EXPLICIT = false;
  43856. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43857. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43858. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43859. _this.INVERTCUBICMAP = false;
  43860. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43861. _this.USESPHERICALINVERTEX = false;
  43862. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43863. _this.LODINREFLECTIONALPHA = false;
  43864. _this.GAMMAREFLECTION = false;
  43865. _this.RADIANCEOCCLUSION = false;
  43866. _this.HORIZONOCCLUSION = false;
  43867. _this.REFRACTION = false;
  43868. _this.REFRACTIONMAP_3D = false;
  43869. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43870. _this.LODINREFRACTIONALPHA = false;
  43871. _this.GAMMAREFRACTION = false;
  43872. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43873. _this.INSTANCES = false;
  43874. _this.NUM_BONE_INFLUENCERS = 0;
  43875. _this.BonesPerMesh = 0;
  43876. _this.NONUNIFORMSCALING = false;
  43877. _this.MORPHTARGETS = false;
  43878. _this.MORPHTARGETS_NORMAL = false;
  43879. _this.MORPHTARGETS_TANGENT = false;
  43880. _this.NUM_MORPH_INFLUENCERS = 0;
  43881. _this.IMAGEPROCESSING = false;
  43882. _this.VIGNETTE = false;
  43883. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43884. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43885. _this.TONEMAPPING = false;
  43886. _this.CONTRAST = false;
  43887. _this.COLORCURVES = false;
  43888. _this.COLORGRADING = false;
  43889. _this.COLORGRADING3D = false;
  43890. _this.SAMPLER3DGREENDEPTH = false;
  43891. _this.SAMPLER3DBGRMAP = false;
  43892. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43893. _this.EXPOSURE = false;
  43894. _this.USEPHYSICALLIGHTFALLOFF = false;
  43895. _this.TWOSIDEDLIGHTING = false;
  43896. _this.SHADOWFLOAT = false;
  43897. _this.CLIPPLANE = false;
  43898. _this.POINTSIZE = false;
  43899. _this.FOG = false;
  43900. _this.LOGARITHMICDEPTH = false;
  43901. _this.FORCENORMALFORWARD = false;
  43902. _this.GEOMETRYAA = false;
  43903. _this.UNLIT = false;
  43904. _this.rebuild();
  43905. return _this;
  43906. }
  43907. /**
  43908. * Resets the PBR Material defines.
  43909. */
  43910. PBRMaterialDefines.prototype.reset = function () {
  43911. _super.prototype.reset.call(this);
  43912. this.ALPHATESTVALUE = "0.5";
  43913. this.PBR = true;
  43914. };
  43915. return PBRMaterialDefines;
  43916. }(BABYLON.MaterialDefines));
  43917. /**
  43918. * The Physically based material base class of BJS.
  43919. *
  43920. * This offers the main features of a standard PBR material.
  43921. * For more information, please refer to the documentation :
  43922. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43923. */
  43924. var PBRBaseMaterial = /** @class */ (function (_super) {
  43925. __extends(PBRBaseMaterial, _super);
  43926. /**
  43927. * Instantiates a new PBRMaterial instance.
  43928. *
  43929. * @param name The material name
  43930. * @param scene The scene the material will be use in.
  43931. */
  43932. function PBRBaseMaterial(name, scene) {
  43933. var _this = _super.call(this, name, scene) || this;
  43934. /**
  43935. * Intensity of the direct lights e.g. the four lights available in your scene.
  43936. * This impacts both the direct diffuse and specular highlights.
  43937. */
  43938. _this._directIntensity = 1.0;
  43939. /**
  43940. * Intensity of the emissive part of the material.
  43941. * This helps controlling the emissive effect without modifying the emissive color.
  43942. */
  43943. _this._emissiveIntensity = 1.0;
  43944. /**
  43945. * Intensity of the environment e.g. how much the environment will light the object
  43946. * either through harmonics for rough material or through the refelction for shiny ones.
  43947. */
  43948. _this._environmentIntensity = 1.0;
  43949. /**
  43950. * This is a special control allowing the reduction of the specular highlights coming from the
  43951. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43952. */
  43953. _this._specularIntensity = 1.0;
  43954. /**
  43955. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43956. */
  43957. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43958. /**
  43959. * Debug Control allowing disabling the bump map on this material.
  43960. */
  43961. _this._disableBumpMap = false;
  43962. /**
  43963. * AKA Occlusion Texture Intensity in other nomenclature.
  43964. */
  43965. _this._ambientTextureStrength = 1.0;
  43966. /**
  43967. * The color of a material in ambient lighting.
  43968. */
  43969. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43970. /**
  43971. * AKA Diffuse Color in other nomenclature.
  43972. */
  43973. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43974. /**
  43975. * AKA Specular Color in other nomenclature.
  43976. */
  43977. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43978. /**
  43979. * The color applied when light is reflected from a material.
  43980. */
  43981. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43982. /**
  43983. * The color applied when light is emitted from a material.
  43984. */
  43985. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43986. /**
  43987. * AKA Glossiness in other nomenclature.
  43988. */
  43989. _this._microSurface = 0.9;
  43990. /**
  43991. * source material index of refraction (IOR)' / 'destination material IOR.
  43992. */
  43993. _this._indexOfRefraction = 0.66;
  43994. /**
  43995. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43996. */
  43997. _this._invertRefractionY = false;
  43998. /**
  43999. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44000. * Materials half opaque for instance using refraction could benefit from this control.
  44001. */
  44002. _this._linkRefractionWithTransparency = false;
  44003. /**
  44004. * Specifies that the material will use the light map as a show map.
  44005. */
  44006. _this._useLightmapAsShadowmap = false;
  44007. /**
  44008. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44009. * makes the reflect vector face the model (under horizon).
  44010. */
  44011. _this._useHorizonOcclusion = true;
  44012. /**
  44013. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44014. * too much the area relying on ambient texture to define their ambient occlusion.
  44015. */
  44016. _this._useRadianceOcclusion = true;
  44017. /**
  44018. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44019. */
  44020. _this._useAlphaFromAlbedoTexture = false;
  44021. /**
  44022. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44023. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44024. */
  44025. _this._useSpecularOverAlpha = true;
  44026. /**
  44027. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44028. */
  44029. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44030. /**
  44031. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44032. */
  44033. _this._useRoughnessFromMetallicTextureAlpha = true;
  44034. /**
  44035. * Specifies if the metallic texture contains the roughness information in its green channel.
  44036. */
  44037. _this._useRoughnessFromMetallicTextureGreen = false;
  44038. /**
  44039. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44040. */
  44041. _this._useMetallnessFromMetallicTextureBlue = false;
  44042. /**
  44043. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44044. */
  44045. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44046. /**
  44047. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44048. */
  44049. _this._useAmbientInGrayScale = false;
  44050. /**
  44051. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44052. * The material will try to infer what glossiness each pixel should be.
  44053. */
  44054. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44055. /**
  44056. * BJS is using an harcoded light falloff based on a manually sets up range.
  44057. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44058. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44059. */
  44060. _this._usePhysicalLightFalloff = true;
  44061. /**
  44062. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44063. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44064. */
  44065. _this._useRadianceOverAlpha = true;
  44066. /**
  44067. * Allows using an object space normal map (instead of tangent space).
  44068. */
  44069. _this._useObjectSpaceNormalMap = false;
  44070. /**
  44071. * Allows using the bump map in parallax mode.
  44072. */
  44073. _this._useParallax = false;
  44074. /**
  44075. * Allows using the bump map in parallax occlusion mode.
  44076. */
  44077. _this._useParallaxOcclusion = false;
  44078. /**
  44079. * Controls the scale bias of the parallax mode.
  44080. */
  44081. _this._parallaxScaleBias = 0.05;
  44082. /**
  44083. * If sets to true, disables all the lights affecting the material.
  44084. */
  44085. _this._disableLighting = false;
  44086. /**
  44087. * Number of Simultaneous lights allowed on the material.
  44088. */
  44089. _this._maxSimultaneousLights = 4;
  44090. /**
  44091. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44092. */
  44093. _this._invertNormalMapX = false;
  44094. /**
  44095. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44096. */
  44097. _this._invertNormalMapY = false;
  44098. /**
  44099. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44100. */
  44101. _this._twoSidedLighting = false;
  44102. /**
  44103. * Defines the alpha limits in alpha test mode.
  44104. */
  44105. _this._alphaCutOff = 0.4;
  44106. /**
  44107. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44108. */
  44109. _this._forceAlphaTest = false;
  44110. /**
  44111. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44112. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44113. */
  44114. _this._useAlphaFresnel = false;
  44115. /**
  44116. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44117. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44118. */
  44119. _this._useLinearAlphaFresnel = false;
  44120. /**
  44121. * The transparency mode of the material.
  44122. */
  44123. _this._transparencyMode = null;
  44124. /**
  44125. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44126. * from cos thetav and roughness:
  44127. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44128. */
  44129. _this._environmentBRDFTexture = null;
  44130. /**
  44131. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44132. */
  44133. _this._forceIrradianceInFragment = false;
  44134. /**
  44135. * Force normal to face away from face.
  44136. */
  44137. _this._forceNormalForward = false;
  44138. /**
  44139. * Enables specular anti aliasing in the PBR shader.
  44140. * It will both interacts on the Geometry for analytical and IBL lighting.
  44141. * It also prefilter the roughness map based on the bump values.
  44142. */
  44143. _this._enableSpecularAntiAliasing = false;
  44144. /**
  44145. * Stores the available render targets.
  44146. */
  44147. _this._renderTargets = new BABYLON.SmartArray(16);
  44148. /**
  44149. * Sets the global ambient color for the material used in lighting calculations.
  44150. */
  44151. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44152. /**
  44153. * If set to true, no lighting calculations will be applied.
  44154. */
  44155. _this._unlit = false;
  44156. // Setup the default processing configuration to the scene.
  44157. _this._attachImageProcessingConfiguration(null);
  44158. _this.getRenderTargetTextures = function () {
  44159. _this._renderTargets.reset();
  44160. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44161. _this._renderTargets.push(_this._reflectionTexture);
  44162. }
  44163. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44164. _this._renderTargets.push(_this._refractionTexture);
  44165. }
  44166. return _this._renderTargets;
  44167. };
  44168. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44169. return _this;
  44170. }
  44171. /**
  44172. * Attaches a new image processing configuration to the PBR Material.
  44173. * @param configuration
  44174. */
  44175. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44176. var _this = this;
  44177. if (configuration === this._imageProcessingConfiguration) {
  44178. return;
  44179. }
  44180. // Detaches observer.
  44181. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44182. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44183. }
  44184. // Pick the scene configuration if needed.
  44185. if (!configuration) {
  44186. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44187. }
  44188. else {
  44189. this._imageProcessingConfiguration = configuration;
  44190. }
  44191. // Attaches observer.
  44192. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44193. _this._markAllSubMeshesAsImageProcessingDirty();
  44194. });
  44195. };
  44196. /**
  44197. * Gets the name of the material class.
  44198. */
  44199. PBRBaseMaterial.prototype.getClassName = function () {
  44200. return "PBRBaseMaterial";
  44201. };
  44202. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44203. /**
  44204. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44205. */
  44206. get: function () {
  44207. return this._useLogarithmicDepth;
  44208. },
  44209. /**
  44210. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44211. */
  44212. set: function (value) {
  44213. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44219. /**
  44220. * Gets the current transparency mode.
  44221. */
  44222. get: function () {
  44223. return this._transparencyMode;
  44224. },
  44225. /**
  44226. * Sets the transparency mode of the material.
  44227. */
  44228. set: function (value) {
  44229. if (this._transparencyMode === value) {
  44230. return;
  44231. }
  44232. this._transparencyMode = value;
  44233. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44234. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44235. },
  44236. enumerable: true,
  44237. configurable: true
  44238. });
  44239. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44240. /**
  44241. * Returns true if alpha blending should be disabled.
  44242. */
  44243. get: function () {
  44244. return (this._linkRefractionWithTransparency ||
  44245. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44246. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44247. },
  44248. enumerable: true,
  44249. configurable: true
  44250. });
  44251. /**
  44252. * Specifies whether or not this material should be rendered in alpha blend mode.
  44253. */
  44254. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44255. if (this._disableAlphaBlending) {
  44256. return false;
  44257. }
  44258. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44259. };
  44260. /**
  44261. * Specifies if the mesh will require alpha blending.
  44262. * @param mesh - BJS mesh.
  44263. */
  44264. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44265. if (this._disableAlphaBlending) {
  44266. return false;
  44267. }
  44268. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44269. };
  44270. /**
  44271. * Specifies whether or not this material should be rendered in alpha test mode.
  44272. */
  44273. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44274. if (this._forceAlphaTest) {
  44275. return true;
  44276. }
  44277. if (this._linkRefractionWithTransparency) {
  44278. return false;
  44279. }
  44280. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44281. };
  44282. /**
  44283. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44284. */
  44285. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44286. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44287. };
  44288. /**
  44289. * Gets the texture used for the alpha test.
  44290. */
  44291. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44292. return this._albedoTexture;
  44293. };
  44294. /**
  44295. * Specifies that the submesh is ready to be used.
  44296. * @param mesh - BJS mesh.
  44297. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44298. * @param useInstances - Specifies that instances should be used.
  44299. * @returns - boolean indicating that the submesh is ready or not.
  44300. */
  44301. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44302. if (subMesh.effect && this.isFrozen) {
  44303. if (this._wasPreviouslyReady) {
  44304. return true;
  44305. }
  44306. }
  44307. if (!subMesh._materialDefines) {
  44308. subMesh._materialDefines = new PBRMaterialDefines();
  44309. }
  44310. var defines = subMesh._materialDefines;
  44311. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44312. if (defines._renderId === this.getScene().getRenderId()) {
  44313. return true;
  44314. }
  44315. }
  44316. var scene = this.getScene();
  44317. var engine = scene.getEngine();
  44318. if (defines._areTexturesDirty) {
  44319. if (scene.texturesEnabled) {
  44320. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44321. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44322. return false;
  44323. }
  44324. }
  44325. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44326. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44327. return false;
  44328. }
  44329. }
  44330. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44331. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44332. return false;
  44333. }
  44334. }
  44335. var reflectionTexture = this._getReflectionTexture();
  44336. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44337. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44338. return false;
  44339. }
  44340. }
  44341. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44342. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44343. return false;
  44344. }
  44345. }
  44346. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44347. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44348. return false;
  44349. }
  44350. }
  44351. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44352. if (this._metallicTexture) {
  44353. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44354. return false;
  44355. }
  44356. }
  44357. else if (this._reflectivityTexture) {
  44358. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44359. return false;
  44360. }
  44361. }
  44362. if (this._microSurfaceTexture) {
  44363. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44364. return false;
  44365. }
  44366. }
  44367. }
  44368. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44369. // Bump texture cannot be not blocking.
  44370. if (!this._bumpTexture.isReady()) {
  44371. return false;
  44372. }
  44373. }
  44374. var refractionTexture = this._getRefractionTexture();
  44375. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44376. if (!refractionTexture.isReadyOrNotBlocking()) {
  44377. return false;
  44378. }
  44379. }
  44380. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44381. // This is blocking.
  44382. if (!this._environmentBRDFTexture.isReady()) {
  44383. return false;
  44384. }
  44385. }
  44386. }
  44387. }
  44388. if (defines._areImageProcessingDirty) {
  44389. if (!this._imageProcessingConfiguration.isReady()) {
  44390. return false;
  44391. }
  44392. }
  44393. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44394. mesh.createNormals(true);
  44395. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44396. }
  44397. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44398. if (effect) {
  44399. scene.resetCachedMaterial();
  44400. subMesh.setEffect(effect, defines);
  44401. this.buildUniformLayout();
  44402. }
  44403. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44404. return false;
  44405. }
  44406. defines._renderId = scene.getRenderId();
  44407. this._wasPreviouslyReady = true;
  44408. return true;
  44409. };
  44410. /**
  44411. * Specifies if the material uses metallic roughness workflow.
  44412. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44413. */
  44414. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44415. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44416. return true;
  44417. }
  44418. return false;
  44419. };
  44420. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44421. if (onCompiled === void 0) { onCompiled = null; }
  44422. if (onError === void 0) { onError = null; }
  44423. if (useInstances === void 0) { useInstances = null; }
  44424. if (useClipPlane === void 0) { useClipPlane = null; }
  44425. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44426. if (!defines.isDirty) {
  44427. return null;
  44428. }
  44429. defines.markAsProcessed();
  44430. var scene = this.getScene();
  44431. var engine = scene.getEngine();
  44432. // Fallbacks
  44433. var fallbacks = new BABYLON.EffectFallbacks();
  44434. var fallbackRank = 0;
  44435. if (defines.USESPHERICALINVERTEX) {
  44436. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44437. }
  44438. if (defines.FOG) {
  44439. fallbacks.addFallback(fallbackRank, "FOG");
  44440. }
  44441. if (defines.POINTSIZE) {
  44442. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44443. }
  44444. if (defines.LOGARITHMICDEPTH) {
  44445. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44446. }
  44447. if (defines.PARALLAX) {
  44448. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44449. }
  44450. if (defines.PARALLAXOCCLUSION) {
  44451. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44452. }
  44453. if (defines.ENVIRONMENTBRDF) {
  44454. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44455. }
  44456. if (defines.TANGENT) {
  44457. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44458. }
  44459. if (defines.BUMP) {
  44460. fallbacks.addFallback(fallbackRank++, "BUMP");
  44461. }
  44462. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44463. if (defines.SPECULARTERM) {
  44464. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44465. }
  44466. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44467. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44468. }
  44469. if (defines.LIGHTMAP) {
  44470. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44471. }
  44472. if (defines.NORMAL) {
  44473. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44474. }
  44475. if (defines.AMBIENT) {
  44476. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44477. }
  44478. if (defines.EMISSIVE) {
  44479. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44480. }
  44481. if (defines.VERTEXCOLOR) {
  44482. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44483. }
  44484. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44485. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44486. }
  44487. if (defines.MORPHTARGETS) {
  44488. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44489. }
  44490. //Attributes
  44491. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44492. if (defines.NORMAL) {
  44493. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44494. }
  44495. if (defines.TANGENT) {
  44496. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44497. }
  44498. if (defines.UV1) {
  44499. attribs.push(BABYLON.VertexBuffer.UVKind);
  44500. }
  44501. if (defines.UV2) {
  44502. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44503. }
  44504. if (defines.VERTEXCOLOR) {
  44505. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44506. }
  44507. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44508. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44509. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44510. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44511. "vFogInfos", "vFogColor", "pointSize",
  44512. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44513. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44514. "mBones",
  44515. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44516. "vLightingIntensity",
  44517. "logarithmicDepthConstant",
  44518. "vSphericalX", "vSphericalY", "vSphericalZ",
  44519. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44520. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44521. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44522. "vTangentSpaceParams"
  44523. ];
  44524. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44525. "bumpSampler", "lightmapSampler", "opacitySampler",
  44526. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44527. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44528. "microSurfaceSampler", "environmentBrdfSampler"];
  44529. var uniformBuffers = ["Material", "Scene"];
  44530. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44531. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44532. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44533. uniformsNames: uniforms,
  44534. uniformBuffersNames: uniformBuffers,
  44535. samplers: samplers,
  44536. defines: defines,
  44537. maxSimultaneousLights: this._maxSimultaneousLights
  44538. });
  44539. var join = defines.toString();
  44540. return engine.createEffect("pbr", {
  44541. attributes: attribs,
  44542. uniformsNames: uniforms,
  44543. uniformBuffersNames: uniformBuffers,
  44544. samplers: samplers,
  44545. defines: join,
  44546. fallbacks: fallbacks,
  44547. onCompiled: onCompiled,
  44548. onError: onError,
  44549. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44550. }, engine);
  44551. };
  44552. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44553. if (useInstances === void 0) { useInstances = null; }
  44554. if (useClipPlane === void 0) { useClipPlane = null; }
  44555. var scene = this.getScene();
  44556. var engine = scene.getEngine();
  44557. // Lights
  44558. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44559. defines._needNormals = true;
  44560. // Textures
  44561. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44562. if (defines._areTexturesDirty) {
  44563. defines._needUVs = false;
  44564. if (scene.texturesEnabled) {
  44565. if (scene.getEngine().getCaps().textureLOD) {
  44566. defines.LODBASEDMICROSFURACE = true;
  44567. }
  44568. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44570. }
  44571. else {
  44572. defines.ALBEDO = false;
  44573. }
  44574. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44575. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44576. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44577. }
  44578. else {
  44579. defines.AMBIENT = false;
  44580. }
  44581. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44582. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44583. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44584. }
  44585. else {
  44586. defines.OPACITY = false;
  44587. }
  44588. var reflectionTexture = this._getReflectionTexture();
  44589. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44590. defines.REFLECTION = true;
  44591. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44592. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44593. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44594. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44595. defines.INVERTCUBICMAP = true;
  44596. }
  44597. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44598. switch (reflectionTexture.coordinatesMode) {
  44599. case BABYLON.Texture.CUBIC_MODE:
  44600. case BABYLON.Texture.INVCUBIC_MODE:
  44601. defines.REFLECTIONMAP_CUBIC = true;
  44602. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44603. break;
  44604. case BABYLON.Texture.EXPLICIT_MODE:
  44605. defines.REFLECTIONMAP_EXPLICIT = true;
  44606. break;
  44607. case BABYLON.Texture.PLANAR_MODE:
  44608. defines.REFLECTIONMAP_PLANAR = true;
  44609. break;
  44610. case BABYLON.Texture.PROJECTION_MODE:
  44611. defines.REFLECTIONMAP_PROJECTION = true;
  44612. break;
  44613. case BABYLON.Texture.SKYBOX_MODE:
  44614. defines.REFLECTIONMAP_SKYBOX = true;
  44615. break;
  44616. case BABYLON.Texture.SPHERICAL_MODE:
  44617. defines.REFLECTIONMAP_SPHERICAL = true;
  44618. break;
  44619. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44620. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44621. break;
  44622. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44623. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44624. break;
  44625. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44626. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44627. break;
  44628. }
  44629. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44630. if (reflectionTexture.sphericalPolynomial) {
  44631. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44632. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44633. defines.USESPHERICALINVERTEX = false;
  44634. }
  44635. else {
  44636. defines.USESPHERICALINVERTEX = true;
  44637. }
  44638. }
  44639. }
  44640. }
  44641. else {
  44642. defines.REFLECTION = false;
  44643. defines.REFLECTIONMAP_3D = false;
  44644. defines.REFLECTIONMAP_SPHERICAL = false;
  44645. defines.REFLECTIONMAP_PLANAR = false;
  44646. defines.REFLECTIONMAP_CUBIC = false;
  44647. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44648. defines.REFLECTIONMAP_PROJECTION = false;
  44649. defines.REFLECTIONMAP_SKYBOX = false;
  44650. defines.REFLECTIONMAP_EXPLICIT = false;
  44651. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44652. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44653. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44654. defines.INVERTCUBICMAP = false;
  44655. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44656. defines.USESPHERICALINVERTEX = false;
  44657. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44658. defines.LODINREFLECTIONALPHA = false;
  44659. defines.GAMMAREFLECTION = false;
  44660. }
  44661. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44662. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44663. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44664. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44665. }
  44666. else {
  44667. defines.LIGHTMAP = false;
  44668. }
  44669. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44671. }
  44672. else {
  44673. defines.EMISSIVE = false;
  44674. }
  44675. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44676. if (this._metallicTexture) {
  44677. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44678. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44679. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44680. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44681. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44682. }
  44683. else if (this._reflectivityTexture) {
  44684. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44685. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44686. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44687. }
  44688. else {
  44689. defines.REFLECTIVITY = false;
  44690. }
  44691. if (this._microSurfaceTexture) {
  44692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44693. }
  44694. else {
  44695. defines.MICROSURFACEMAP = false;
  44696. }
  44697. }
  44698. else {
  44699. defines.REFLECTIVITY = false;
  44700. defines.MICROSURFACEMAP = false;
  44701. }
  44702. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44704. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44705. defines.PARALLAX = true;
  44706. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44707. }
  44708. else {
  44709. defines.PARALLAX = false;
  44710. }
  44711. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44712. }
  44713. else {
  44714. defines.BUMP = false;
  44715. }
  44716. var refractionTexture = this._getRefractionTexture();
  44717. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44718. defines.REFRACTION = true;
  44719. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44720. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44721. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44722. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44723. if (this._linkRefractionWithTransparency) {
  44724. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44725. }
  44726. }
  44727. else {
  44728. defines.REFRACTION = false;
  44729. }
  44730. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44731. defines.ENVIRONMENTBRDF = true;
  44732. }
  44733. else {
  44734. defines.ENVIRONMENTBRDF = false;
  44735. }
  44736. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44737. defines.ALPHAFROMALBEDO = true;
  44738. }
  44739. else {
  44740. defines.ALPHAFROMALBEDO = false;
  44741. }
  44742. }
  44743. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44744. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44745. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44746. if (!this.backFaceCulling && this._twoSidedLighting) {
  44747. defines.TWOSIDEDLIGHTING = true;
  44748. }
  44749. else {
  44750. defines.TWOSIDEDLIGHTING = false;
  44751. }
  44752. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44753. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44754. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44755. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44756. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44757. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44758. }
  44759. if (defines._areImageProcessingDirty) {
  44760. this._imageProcessingConfiguration.prepareDefines(defines);
  44761. }
  44762. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44763. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44764. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44765. // Misc.
  44766. if (defines._areMiscDirty) {
  44767. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44768. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44769. }
  44770. // Values that need to be evaluated on every frame
  44771. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44772. // Attribs
  44773. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44774. };
  44775. /**
  44776. * Force shader compilation
  44777. */
  44778. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44779. var _this = this;
  44780. var localOptions = __assign({ clipPlane: false }, options);
  44781. var defines = new PBRMaterialDefines();
  44782. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44783. if (effect.isReady()) {
  44784. if (onCompiled) {
  44785. onCompiled(this);
  44786. }
  44787. }
  44788. else {
  44789. effect.onCompileObservable.add(function () {
  44790. if (onCompiled) {
  44791. onCompiled(_this);
  44792. }
  44793. });
  44794. }
  44795. };
  44796. /**
  44797. * Initializes the uniform buffer layout for the shader.
  44798. */
  44799. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44800. // Order is important !
  44801. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44802. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44803. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44804. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44805. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44806. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44807. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44808. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44809. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44810. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44811. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44812. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44813. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44814. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44815. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44816. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44817. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44818. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44819. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44820. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44821. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44822. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44823. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44824. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44825. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44826. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44827. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44828. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44829. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44830. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44831. this._uniformBuffer.addUniform("pointSize", 1);
  44832. this._uniformBuffer.create();
  44833. };
  44834. /**
  44835. * Unbinds the textures.
  44836. */
  44837. PBRBaseMaterial.prototype.unbind = function () {
  44838. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44839. this._uniformBuffer.setTexture("reflectionSampler", null);
  44840. }
  44841. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44842. this._uniformBuffer.setTexture("refractionSampler", null);
  44843. }
  44844. _super.prototype.unbind.call(this);
  44845. };
  44846. /**
  44847. * Binds the submesh data.
  44848. * @param world - The world matrix.
  44849. * @param mesh - The BJS mesh.
  44850. * @param subMesh - A submesh of the BJS mesh.
  44851. */
  44852. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44853. var scene = this.getScene();
  44854. var defines = subMesh._materialDefines;
  44855. if (!defines) {
  44856. return;
  44857. }
  44858. var effect = subMesh.effect;
  44859. if (!effect) {
  44860. return;
  44861. }
  44862. this._activeEffect = effect;
  44863. // Matrices
  44864. this.bindOnlyWorldMatrix(world);
  44865. // Normal Matrix
  44866. if (defines.OBJECTSPACE_NORMALMAP) {
  44867. world.toNormalMatrix(this._normalMatrix);
  44868. this.bindOnlyNormalMatrix(this._normalMatrix);
  44869. }
  44870. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44871. // Bones
  44872. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44873. var reflectionTexture = null;
  44874. if (mustRebind) {
  44875. this._uniformBuffer.bindToEffect(effect, "Material");
  44876. this.bindViewProjection(effect);
  44877. reflectionTexture = this._getReflectionTexture();
  44878. var refractionTexture = this._getRefractionTexture();
  44879. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44880. // Texture uniforms
  44881. if (scene.texturesEnabled) {
  44882. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44883. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44884. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44885. }
  44886. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44887. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44888. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44889. }
  44890. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44891. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44892. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44893. }
  44894. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44895. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44896. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44897. if (reflectionTexture.boundingBoxSize) {
  44898. var cubeTexture = reflectionTexture;
  44899. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44900. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44901. }
  44902. var polynomials = reflectionTexture.sphericalPolynomial;
  44903. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44904. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44905. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44906. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44907. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44908. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44909. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44910. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44911. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44912. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44913. }
  44914. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44915. }
  44916. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44917. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44918. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44919. }
  44920. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44921. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44922. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44923. }
  44924. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44925. if (this._metallicTexture) {
  44926. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44927. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44928. }
  44929. else if (this._reflectivityTexture) {
  44930. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44931. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44932. }
  44933. if (this._microSurfaceTexture) {
  44934. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44935. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44936. }
  44937. }
  44938. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44939. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44940. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44941. if (scene._mirroredCameraPosition) {
  44942. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44943. }
  44944. else {
  44945. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44946. }
  44947. }
  44948. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44949. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44950. var depth = 1.0;
  44951. if (!refractionTexture.isCube) {
  44952. if (refractionTexture.depth) {
  44953. depth = refractionTexture.depth;
  44954. }
  44955. }
  44956. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44957. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44958. }
  44959. }
  44960. // Point size
  44961. if (this.pointsCloud) {
  44962. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44963. }
  44964. // Colors
  44965. if (defines.METALLICWORKFLOW) {
  44966. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44967. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44968. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44969. }
  44970. else {
  44971. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44972. }
  44973. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44974. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44975. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44976. // Misc
  44977. this._lightingInfos.x = this._directIntensity;
  44978. this._lightingInfos.y = this._emissiveIntensity;
  44979. this._lightingInfos.z = this._environmentIntensity;
  44980. this._lightingInfos.w = this._specularIntensity;
  44981. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44982. }
  44983. // Textures
  44984. if (scene.texturesEnabled) {
  44985. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44986. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44987. }
  44988. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44989. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44990. }
  44991. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44992. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44993. }
  44994. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44995. if (defines.LODBASEDMICROSFURACE) {
  44996. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44997. }
  44998. else {
  44999. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45000. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45001. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45002. }
  45003. }
  45004. if (defines.ENVIRONMENTBRDF) {
  45005. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45006. }
  45007. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45008. if (defines.LODBASEDMICROSFURACE) {
  45009. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45010. }
  45011. else {
  45012. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45013. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45014. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45015. }
  45016. }
  45017. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45018. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45019. }
  45020. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45021. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45022. }
  45023. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45024. if (this._metallicTexture) {
  45025. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45026. }
  45027. else if (this._reflectivityTexture) {
  45028. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45029. }
  45030. if (this._microSurfaceTexture) {
  45031. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45032. }
  45033. }
  45034. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45035. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45036. }
  45037. }
  45038. // Clip plane
  45039. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45040. // Colors
  45041. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45042. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45043. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45044. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45045. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45046. }
  45047. if (mustRebind || !this.isFrozen) {
  45048. // Lights
  45049. if (scene.lightsEnabled && !this._disableLighting) {
  45050. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45051. }
  45052. // View
  45053. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45054. this.bindView(effect);
  45055. }
  45056. // Fog
  45057. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45058. // Morph targets
  45059. if (defines.NUM_MORPH_INFLUENCERS) {
  45060. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45061. }
  45062. // image processing
  45063. this._imageProcessingConfiguration.bind(this._activeEffect);
  45064. // Log. depth
  45065. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45066. }
  45067. this._uniformBuffer.update();
  45068. this._afterBind(mesh);
  45069. };
  45070. /**
  45071. * Returns the animatable textures.
  45072. * @returns - Array of animatable textures.
  45073. */
  45074. PBRBaseMaterial.prototype.getAnimatables = function () {
  45075. var results = [];
  45076. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45077. results.push(this._albedoTexture);
  45078. }
  45079. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45080. results.push(this._ambientTexture);
  45081. }
  45082. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45083. results.push(this._opacityTexture);
  45084. }
  45085. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45086. results.push(this._reflectionTexture);
  45087. }
  45088. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45089. results.push(this._emissiveTexture);
  45090. }
  45091. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45092. results.push(this._metallicTexture);
  45093. }
  45094. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45095. results.push(this._reflectivityTexture);
  45096. }
  45097. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45098. results.push(this._bumpTexture);
  45099. }
  45100. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45101. results.push(this._lightmapTexture);
  45102. }
  45103. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45104. results.push(this._refractionTexture);
  45105. }
  45106. return results;
  45107. };
  45108. /**
  45109. * Returns the texture used for reflections.
  45110. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45111. */
  45112. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45113. if (this._reflectionTexture) {
  45114. return this._reflectionTexture;
  45115. }
  45116. return this.getScene().environmentTexture;
  45117. };
  45118. /**
  45119. * Returns the texture used for refraction or null if none is used.
  45120. * @returns - Refection texture if present. If no refraction texture and refraction
  45121. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45122. */
  45123. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45124. if (this._refractionTexture) {
  45125. return this._refractionTexture;
  45126. }
  45127. if (this._linkRefractionWithTransparency) {
  45128. return this.getScene().environmentTexture;
  45129. }
  45130. return null;
  45131. };
  45132. /**
  45133. * Disposes the resources of the material.
  45134. * @param forceDisposeEffect - Forces the disposal of effects.
  45135. * @param forceDisposeTextures - Forces the disposal of all textures.
  45136. */
  45137. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45138. if (forceDisposeTextures) {
  45139. if (this._albedoTexture) {
  45140. this._albedoTexture.dispose();
  45141. }
  45142. if (this._ambientTexture) {
  45143. this._ambientTexture.dispose();
  45144. }
  45145. if (this._opacityTexture) {
  45146. this._opacityTexture.dispose();
  45147. }
  45148. if (this._reflectionTexture) {
  45149. this._reflectionTexture.dispose();
  45150. }
  45151. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45152. this._environmentBRDFTexture.dispose();
  45153. }
  45154. if (this._emissiveTexture) {
  45155. this._emissiveTexture.dispose();
  45156. }
  45157. if (this._metallicTexture) {
  45158. this._metallicTexture.dispose();
  45159. }
  45160. if (this._reflectivityTexture) {
  45161. this._reflectivityTexture.dispose();
  45162. }
  45163. if (this._bumpTexture) {
  45164. this._bumpTexture.dispose();
  45165. }
  45166. if (this._lightmapTexture) {
  45167. this._lightmapTexture.dispose();
  45168. }
  45169. if (this._refractionTexture) {
  45170. this._refractionTexture.dispose();
  45171. }
  45172. }
  45173. this._renderTargets.dispose();
  45174. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45175. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45176. }
  45177. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45178. };
  45179. /**
  45180. * Stores the reflectivity values based on metallic roughness workflow.
  45181. */
  45182. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45183. __decorate([
  45184. BABYLON.serializeAsImageProcessingConfiguration()
  45185. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45186. __decorate([
  45187. BABYLON.serialize()
  45188. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45189. __decorate([
  45190. BABYLON.serialize()
  45191. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45192. return PBRBaseMaterial;
  45193. }(BABYLON.PushMaterial));
  45194. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45195. })(BABYLON || (BABYLON = {}));
  45196. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45197. var BABYLON;
  45198. (function (BABYLON) {
  45199. /**
  45200. * The Physically based simple base material of BJS.
  45201. *
  45202. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45203. * It is used as the base class for both the specGloss and metalRough conventions.
  45204. */
  45205. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45206. __extends(PBRBaseSimpleMaterial, _super);
  45207. /**
  45208. * Instantiates a new PBRMaterial instance.
  45209. *
  45210. * @param name The material name
  45211. * @param scene The scene the material will be use in.
  45212. */
  45213. function PBRBaseSimpleMaterial(name, scene) {
  45214. var _this = _super.call(this, name, scene) || this;
  45215. /**
  45216. * Number of Simultaneous lights allowed on the material.
  45217. */
  45218. _this.maxSimultaneousLights = 4;
  45219. /**
  45220. * If sets to true, disables all the lights affecting the material.
  45221. */
  45222. _this.disableLighting = false;
  45223. /**
  45224. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45225. */
  45226. _this.invertNormalMapX = false;
  45227. /**
  45228. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45229. */
  45230. _this.invertNormalMapY = false;
  45231. /**
  45232. * Emissivie color used to self-illuminate the model.
  45233. */
  45234. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45235. /**
  45236. * Occlusion Channel Strenght.
  45237. */
  45238. _this.occlusionStrength = 1.0;
  45239. _this.useLightmapAsShadowmap = false;
  45240. _this._useAlphaFromAlbedoTexture = true;
  45241. _this._useAmbientInGrayScale = true;
  45242. return _this;
  45243. }
  45244. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45245. /**
  45246. * Gets the current double sided mode.
  45247. */
  45248. get: function () {
  45249. return this._twoSidedLighting;
  45250. },
  45251. /**
  45252. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45253. */
  45254. set: function (value) {
  45255. if (this._twoSidedLighting === value) {
  45256. return;
  45257. }
  45258. this._twoSidedLighting = value;
  45259. this.backFaceCulling = !value;
  45260. this._markAllSubMeshesAsTexturesDirty();
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. /**
  45266. * Return the active textures of the material.
  45267. */
  45268. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45269. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45270. if (this.environmentTexture) {
  45271. activeTextures.push(this.environmentTexture);
  45272. }
  45273. if (this.normalTexture) {
  45274. activeTextures.push(this.normalTexture);
  45275. }
  45276. if (this.emissiveTexture) {
  45277. activeTextures.push(this.emissiveTexture);
  45278. }
  45279. if (this.occlusionTexture) {
  45280. activeTextures.push(this.occlusionTexture);
  45281. }
  45282. if (this.lightmapTexture) {
  45283. activeTextures.push(this.lightmapTexture);
  45284. }
  45285. return activeTextures;
  45286. };
  45287. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45288. if (_super.prototype.hasTexture.call(this, texture)) {
  45289. return true;
  45290. }
  45291. if (this.lightmapTexture === texture) {
  45292. return true;
  45293. }
  45294. return false;
  45295. };
  45296. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45297. return "PBRBaseSimpleMaterial";
  45298. };
  45299. __decorate([
  45300. BABYLON.serialize(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45302. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45303. __decorate([
  45304. BABYLON.serialize(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45306. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45307. __decorate([
  45308. BABYLON.serializeAsTexture(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45310. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45311. __decorate([
  45312. BABYLON.serialize(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45315. __decorate([
  45316. BABYLON.serialize(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45319. __decorate([
  45320. BABYLON.serializeAsTexture(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45322. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45323. __decorate([
  45324. BABYLON.serializeAsColor3("emissive"),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45327. __decorate([
  45328. BABYLON.serializeAsTexture(),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45331. __decorate([
  45332. BABYLON.serialize(),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45334. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsTexture(),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45338. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45339. __decorate([
  45340. BABYLON.serialize(),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45342. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45343. __decorate([
  45344. BABYLON.serialize()
  45345. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45346. __decorate([
  45347. BABYLON.serializeAsTexture(),
  45348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45349. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45350. __decorate([
  45351. BABYLON.serialize(),
  45352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45353. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45354. return PBRBaseSimpleMaterial;
  45355. }(BABYLON.PBRBaseMaterial));
  45356. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45357. })(BABYLON || (BABYLON = {}));
  45358. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45359. var BABYLON;
  45360. (function (BABYLON) {
  45361. /**
  45362. * The Physically based material of BJS.
  45363. *
  45364. * This offers the main features of a standard PBR material.
  45365. * For more information, please refer to the documentation :
  45366. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45367. */
  45368. var PBRMaterial = /** @class */ (function (_super) {
  45369. __extends(PBRMaterial, _super);
  45370. /**
  45371. * Instantiates a new PBRMaterial instance.
  45372. *
  45373. * @param name The material name
  45374. * @param scene The scene the material will be use in.
  45375. */
  45376. function PBRMaterial(name, scene) {
  45377. var _this = _super.call(this, name, scene) || this;
  45378. /**
  45379. * Intensity of the direct lights e.g. the four lights available in your scene.
  45380. * This impacts both the direct diffuse and specular highlights.
  45381. */
  45382. _this.directIntensity = 1.0;
  45383. /**
  45384. * Intensity of the emissive part of the material.
  45385. * This helps controlling the emissive effect without modifying the emissive color.
  45386. */
  45387. _this.emissiveIntensity = 1.0;
  45388. /**
  45389. * Intensity of the environment e.g. how much the environment will light the object
  45390. * either through harmonics for rough material or through the refelction for shiny ones.
  45391. */
  45392. _this.environmentIntensity = 1.0;
  45393. /**
  45394. * This is a special control allowing the reduction of the specular highlights coming from the
  45395. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45396. */
  45397. _this.specularIntensity = 1.0;
  45398. /**
  45399. * Debug Control allowing disabling the bump map on this material.
  45400. */
  45401. _this.disableBumpMap = false;
  45402. /**
  45403. * AKA Occlusion Texture Intensity in other nomenclature.
  45404. */
  45405. _this.ambientTextureStrength = 1.0;
  45406. /**
  45407. * The color of a material in ambient lighting.
  45408. */
  45409. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45410. /**
  45411. * AKA Diffuse Color in other nomenclature.
  45412. */
  45413. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45414. /**
  45415. * AKA Specular Color in other nomenclature.
  45416. */
  45417. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45418. /**
  45419. * The color reflected from the material.
  45420. */
  45421. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45422. /**
  45423. * The color emitted from the material.
  45424. */
  45425. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45426. /**
  45427. * AKA Glossiness in other nomenclature.
  45428. */
  45429. _this.microSurface = 1.0;
  45430. /**
  45431. * source material index of refraction (IOR)' / 'destination material IOR.
  45432. */
  45433. _this.indexOfRefraction = 0.66;
  45434. /**
  45435. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45436. */
  45437. _this.invertRefractionY = false;
  45438. /**
  45439. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45440. * Materials half opaque for instance using refraction could benefit from this control.
  45441. */
  45442. _this.linkRefractionWithTransparency = false;
  45443. _this.useLightmapAsShadowmap = false;
  45444. /**
  45445. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45446. */
  45447. _this.useAlphaFromAlbedoTexture = false;
  45448. /**
  45449. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45450. */
  45451. _this.forceAlphaTest = false;
  45452. /**
  45453. * Defines the alpha limits in alpha test mode.
  45454. */
  45455. _this.alphaCutOff = 0.4;
  45456. /**
  45457. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45458. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45459. */
  45460. _this.useSpecularOverAlpha = true;
  45461. /**
  45462. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45463. */
  45464. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45465. /**
  45466. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45467. */
  45468. _this.useRoughnessFromMetallicTextureAlpha = true;
  45469. /**
  45470. * Specifies if the metallic texture contains the roughness information in its green channel.
  45471. */
  45472. _this.useRoughnessFromMetallicTextureGreen = false;
  45473. /**
  45474. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45475. */
  45476. _this.useMetallnessFromMetallicTextureBlue = false;
  45477. /**
  45478. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45479. */
  45480. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45481. /**
  45482. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45483. */
  45484. _this.useAmbientInGrayScale = false;
  45485. /**
  45486. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45487. * The material will try to infer what glossiness each pixel should be.
  45488. */
  45489. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45490. /**
  45491. * BJS is using an harcoded light falloff based on a manually sets up range.
  45492. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45493. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45494. */
  45495. _this.usePhysicalLightFalloff = true;
  45496. /**
  45497. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45498. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45499. */
  45500. _this.useRadianceOverAlpha = true;
  45501. /**
  45502. * Allows using an object space normal map (instead of tangent space).
  45503. */
  45504. _this.useObjectSpaceNormalMap = false;
  45505. /**
  45506. * Allows using the bump map in parallax mode.
  45507. */
  45508. _this.useParallax = false;
  45509. /**
  45510. * Allows using the bump map in parallax occlusion mode.
  45511. */
  45512. _this.useParallaxOcclusion = false;
  45513. /**
  45514. * Controls the scale bias of the parallax mode.
  45515. */
  45516. _this.parallaxScaleBias = 0.05;
  45517. /**
  45518. * If sets to true, disables all the lights affecting the material.
  45519. */
  45520. _this.disableLighting = false;
  45521. /**
  45522. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45523. */
  45524. _this.forceIrradianceInFragment = false;
  45525. /**
  45526. * Number of Simultaneous lights allowed on the material.
  45527. */
  45528. _this.maxSimultaneousLights = 4;
  45529. /**
  45530. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45531. */
  45532. _this.invertNormalMapX = false;
  45533. /**
  45534. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45535. */
  45536. _this.invertNormalMapY = false;
  45537. /**
  45538. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45539. */
  45540. _this.twoSidedLighting = false;
  45541. /**
  45542. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45543. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45544. */
  45545. _this.useAlphaFresnel = false;
  45546. /**
  45547. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45548. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45549. */
  45550. _this.useLinearAlphaFresnel = false;
  45551. /**
  45552. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45553. * And/Or occlude the blended part.
  45554. */
  45555. _this.environmentBRDFTexture = null;
  45556. /**
  45557. * Force normal to face away from face.
  45558. */
  45559. _this.forceNormalForward = false;
  45560. /**
  45561. * Enables specular anti aliasing in the PBR shader.
  45562. * It will both interacts on the Geometry for analytical and IBL lighting.
  45563. * It also prefilter the roughness map based on the bump values.
  45564. */
  45565. _this.enableSpecularAntiAliasing = false;
  45566. /**
  45567. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45568. * makes the reflect vector face the model (under horizon).
  45569. */
  45570. _this.useHorizonOcclusion = true;
  45571. /**
  45572. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45573. * too much the area relying on ambient texture to define their ambient occlusion.
  45574. */
  45575. _this.useRadianceOcclusion = true;
  45576. /**
  45577. * If set to true, no lighting calculations will be applied.
  45578. */
  45579. _this.unlit = false;
  45580. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45581. return _this;
  45582. }
  45583. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45584. /**
  45585. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45586. */
  45587. get: function () {
  45588. return this._PBRMATERIAL_OPAQUE;
  45589. },
  45590. enumerable: true,
  45591. configurable: true
  45592. });
  45593. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45594. /**
  45595. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45596. */
  45597. get: function () {
  45598. return this._PBRMATERIAL_ALPHATEST;
  45599. },
  45600. enumerable: true,
  45601. configurable: true
  45602. });
  45603. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45604. /**
  45605. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45606. */
  45607. get: function () {
  45608. return this._PBRMATERIAL_ALPHABLEND;
  45609. },
  45610. enumerable: true,
  45611. configurable: true
  45612. });
  45613. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45614. /**
  45615. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45616. * They are also discarded below the alpha cutoff threshold to improve performances.
  45617. */
  45618. get: function () {
  45619. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45620. },
  45621. enumerable: true,
  45622. configurable: true
  45623. });
  45624. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45625. /**
  45626. * Gets the image processing configuration used either in this material.
  45627. */
  45628. get: function () {
  45629. return this._imageProcessingConfiguration;
  45630. },
  45631. /**
  45632. * Sets the Default image processing configuration used either in the this material.
  45633. *
  45634. * If sets to null, the scene one is in use.
  45635. */
  45636. set: function (value) {
  45637. this._attachImageProcessingConfiguration(value);
  45638. // Ensure the effect will be rebuilt.
  45639. this._markAllSubMeshesAsTexturesDirty();
  45640. },
  45641. enumerable: true,
  45642. configurable: true
  45643. });
  45644. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45645. /**
  45646. * Gets wether the color curves effect is enabled.
  45647. */
  45648. get: function () {
  45649. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45650. },
  45651. /**
  45652. * Sets wether the color curves effect is enabled.
  45653. */
  45654. set: function (value) {
  45655. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45656. },
  45657. enumerable: true,
  45658. configurable: true
  45659. });
  45660. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45661. /**
  45662. * Gets wether the color grading effect is enabled.
  45663. */
  45664. get: function () {
  45665. return this.imageProcessingConfiguration.colorGradingEnabled;
  45666. },
  45667. /**
  45668. * Gets wether the color grading effect is enabled.
  45669. */
  45670. set: function (value) {
  45671. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45672. },
  45673. enumerable: true,
  45674. configurable: true
  45675. });
  45676. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45677. /**
  45678. * Gets wether tonemapping is enabled or not.
  45679. */
  45680. get: function () {
  45681. return this._imageProcessingConfiguration.toneMappingEnabled;
  45682. },
  45683. /**
  45684. * Sets wether tonemapping is enabled or not
  45685. */
  45686. set: function (value) {
  45687. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45688. },
  45689. enumerable: true,
  45690. configurable: true
  45691. });
  45692. ;
  45693. ;
  45694. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45695. /**
  45696. * The camera exposure used on this material.
  45697. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45698. * This corresponds to a photographic exposure.
  45699. */
  45700. get: function () {
  45701. return this._imageProcessingConfiguration.exposure;
  45702. },
  45703. /**
  45704. * The camera exposure used on this material.
  45705. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45706. * This corresponds to a photographic exposure.
  45707. */
  45708. set: function (value) {
  45709. this._imageProcessingConfiguration.exposure = value;
  45710. },
  45711. enumerable: true,
  45712. configurable: true
  45713. });
  45714. ;
  45715. ;
  45716. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45717. /**
  45718. * Gets The camera contrast used on this material.
  45719. */
  45720. get: function () {
  45721. return this._imageProcessingConfiguration.contrast;
  45722. },
  45723. /**
  45724. * Sets The camera contrast used on this material.
  45725. */
  45726. set: function (value) {
  45727. this._imageProcessingConfiguration.contrast = value;
  45728. },
  45729. enumerable: true,
  45730. configurable: true
  45731. });
  45732. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45733. /**
  45734. * Gets the Color Grading 2D Lookup Texture.
  45735. */
  45736. get: function () {
  45737. return this._imageProcessingConfiguration.colorGradingTexture;
  45738. },
  45739. /**
  45740. * Sets the Color Grading 2D Lookup Texture.
  45741. */
  45742. set: function (value) {
  45743. this._imageProcessingConfiguration.colorGradingTexture = value;
  45744. },
  45745. enumerable: true,
  45746. configurable: true
  45747. });
  45748. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45749. /**
  45750. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45751. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45752. * 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;
  45753. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45754. */
  45755. get: function () {
  45756. return this._imageProcessingConfiguration.colorCurves;
  45757. },
  45758. /**
  45759. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45760. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45761. * 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;
  45762. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45763. */
  45764. set: function (value) {
  45765. this._imageProcessingConfiguration.colorCurves = value;
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. /**
  45771. * Returns the name of this material class.
  45772. */
  45773. PBRMaterial.prototype.getClassName = function () {
  45774. return "PBRMaterial";
  45775. };
  45776. /**
  45777. * Returns an array of the actively used textures.
  45778. * @returns - Array of BaseTextures
  45779. */
  45780. PBRMaterial.prototype.getActiveTextures = function () {
  45781. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45782. if (this._albedoTexture) {
  45783. activeTextures.push(this._albedoTexture);
  45784. }
  45785. if (this._ambientTexture) {
  45786. activeTextures.push(this._ambientTexture);
  45787. }
  45788. if (this._opacityTexture) {
  45789. activeTextures.push(this._opacityTexture);
  45790. }
  45791. if (this._reflectionTexture) {
  45792. activeTextures.push(this._reflectionTexture);
  45793. }
  45794. if (this._emissiveTexture) {
  45795. activeTextures.push(this._emissiveTexture);
  45796. }
  45797. if (this._reflectivityTexture) {
  45798. activeTextures.push(this._reflectivityTexture);
  45799. }
  45800. if (this._metallicTexture) {
  45801. activeTextures.push(this._metallicTexture);
  45802. }
  45803. if (this._microSurfaceTexture) {
  45804. activeTextures.push(this._microSurfaceTexture);
  45805. }
  45806. if (this._bumpTexture) {
  45807. activeTextures.push(this._bumpTexture);
  45808. }
  45809. if (this._lightmapTexture) {
  45810. activeTextures.push(this._lightmapTexture);
  45811. }
  45812. if (this._refractionTexture) {
  45813. activeTextures.push(this._refractionTexture);
  45814. }
  45815. return activeTextures;
  45816. };
  45817. /**
  45818. * Checks to see if a texture is used in the material.
  45819. * @param texture - Base texture to use.
  45820. * @returns - Boolean specifying if a texture is used in the material.
  45821. */
  45822. PBRMaterial.prototype.hasTexture = function (texture) {
  45823. if (_super.prototype.hasTexture.call(this, texture)) {
  45824. return true;
  45825. }
  45826. if (this._albedoTexture === texture) {
  45827. return true;
  45828. }
  45829. if (this._ambientTexture === texture) {
  45830. return true;
  45831. }
  45832. if (this._opacityTexture === texture) {
  45833. return true;
  45834. }
  45835. if (this._reflectionTexture === texture) {
  45836. return true;
  45837. }
  45838. if (this._reflectivityTexture === texture) {
  45839. return true;
  45840. }
  45841. if (this._metallicTexture === texture) {
  45842. return true;
  45843. }
  45844. if (this._microSurfaceTexture === texture) {
  45845. return true;
  45846. }
  45847. if (this._bumpTexture === texture) {
  45848. return true;
  45849. }
  45850. if (this._lightmapTexture === texture) {
  45851. return true;
  45852. }
  45853. if (this._refractionTexture === texture) {
  45854. return true;
  45855. }
  45856. return false;
  45857. };
  45858. /**
  45859. * Makes a duplicate of the current material.
  45860. * @param name - name to use for the new material.
  45861. */
  45862. PBRMaterial.prototype.clone = function (name) {
  45863. var _this = this;
  45864. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45865. clone.id = name;
  45866. clone.name = name;
  45867. return clone;
  45868. };
  45869. /**
  45870. * Serializes this PBR Material.
  45871. * @returns - An object with the serialized material.
  45872. */
  45873. PBRMaterial.prototype.serialize = function () {
  45874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45875. serializationObject.customType = "BABYLON.PBRMaterial";
  45876. return serializationObject;
  45877. };
  45878. // Statics
  45879. /**
  45880. * Parses a PBR Material from a serialized object.
  45881. * @param source - Serialized object.
  45882. * @param scene - BJS scene instance.
  45883. * @param rootUrl - url for the scene object
  45884. * @returns - PBRMaterial
  45885. */
  45886. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45887. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45888. };
  45889. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45890. /**
  45891. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45892. */
  45893. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45894. /**
  45895. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45896. */
  45897. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45898. /**
  45899. * 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.
  45900. * They are also discarded below the alpha cutoff threshold to improve performances.
  45901. */
  45902. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45903. __decorate([
  45904. BABYLON.serialize(),
  45905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45906. ], PBRMaterial.prototype, "directIntensity", void 0);
  45907. __decorate([
  45908. BABYLON.serialize(),
  45909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45910. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45911. __decorate([
  45912. BABYLON.serialize(),
  45913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45914. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45915. __decorate([
  45916. BABYLON.serialize(),
  45917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45918. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45919. __decorate([
  45920. BABYLON.serialize(),
  45921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45922. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45923. __decorate([
  45924. BABYLON.serializeAsTexture(),
  45925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45926. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45927. __decorate([
  45928. BABYLON.serializeAsTexture(),
  45929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45930. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45931. __decorate([
  45932. BABYLON.serialize(),
  45933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45934. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45935. __decorate([
  45936. BABYLON.serializeAsTexture(),
  45937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45938. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45939. __decorate([
  45940. BABYLON.serializeAsTexture(),
  45941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45942. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45943. __decorate([
  45944. BABYLON.serializeAsTexture(),
  45945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45946. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45947. __decorate([
  45948. BABYLON.serializeAsTexture(),
  45949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45950. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45951. __decorate([
  45952. BABYLON.serializeAsTexture(),
  45953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45954. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45955. __decorate([
  45956. BABYLON.serialize(),
  45957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45958. ], PBRMaterial.prototype, "metallic", void 0);
  45959. __decorate([
  45960. BABYLON.serialize(),
  45961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45962. ], PBRMaterial.prototype, "roughness", void 0);
  45963. __decorate([
  45964. BABYLON.serializeAsTexture(),
  45965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45966. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45967. __decorate([
  45968. BABYLON.serializeAsTexture(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45970. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45971. __decorate([
  45972. BABYLON.serializeAsTexture(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45974. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45975. __decorate([
  45976. BABYLON.serializeAsTexture(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45978. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45979. __decorate([
  45980. BABYLON.serializeAsColor3("ambient"),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45982. ], PBRMaterial.prototype, "ambientColor", void 0);
  45983. __decorate([
  45984. BABYLON.serializeAsColor3("albedo"),
  45985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45986. ], PBRMaterial.prototype, "albedoColor", void 0);
  45987. __decorate([
  45988. BABYLON.serializeAsColor3("reflectivity"),
  45989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45990. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45991. __decorate([
  45992. BABYLON.serializeAsColor3("reflection"),
  45993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45994. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45995. __decorate([
  45996. BABYLON.serializeAsColor3("emissive"),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMaterial.prototype, "microSurface", void 0);
  46003. __decorate([
  46004. BABYLON.serialize(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46006. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46007. __decorate([
  46008. BABYLON.serialize(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46010. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46011. __decorate([
  46012. BABYLON.serialize(),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46014. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46015. __decorate([
  46016. BABYLON.serialize(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46018. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46019. __decorate([
  46020. BABYLON.serialize(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46022. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46023. __decorate([
  46024. BABYLON.serialize(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46026. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46027. __decorate([
  46028. BABYLON.serialize(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46030. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46031. __decorate([
  46032. BABYLON.serialize(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46034. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46035. __decorate([
  46036. BABYLON.serialize(),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46038. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46039. __decorate([
  46040. BABYLON.serialize(),
  46041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46042. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46043. __decorate([
  46044. BABYLON.serialize(),
  46045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46046. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46047. __decorate([
  46048. BABYLON.serialize(),
  46049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46050. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46051. __decorate([
  46052. BABYLON.serialize(),
  46053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46054. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46055. __decorate([
  46056. BABYLON.serialize(),
  46057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46058. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46059. __decorate([
  46060. BABYLON.serialize(),
  46061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46062. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46063. __decorate([
  46064. BABYLON.serialize(),
  46065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46066. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46067. __decorate([
  46068. BABYLON.serialize(),
  46069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46070. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46071. __decorate([
  46072. BABYLON.serialize(),
  46073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46074. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46075. __decorate([
  46076. BABYLON.serialize(),
  46077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46078. ], PBRMaterial.prototype, "useParallax", void 0);
  46079. __decorate([
  46080. BABYLON.serialize(),
  46081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46082. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46083. __decorate([
  46084. BABYLON.serialize(),
  46085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46086. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46087. __decorate([
  46088. BABYLON.serialize(),
  46089. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46090. ], PBRMaterial.prototype, "disableLighting", void 0);
  46091. __decorate([
  46092. BABYLON.serialize(),
  46093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46094. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46095. __decorate([
  46096. BABYLON.serialize(),
  46097. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46098. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46099. __decorate([
  46100. BABYLON.serialize(),
  46101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46102. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46103. __decorate([
  46104. BABYLON.serialize(),
  46105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46106. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46107. __decorate([
  46108. BABYLON.serialize(),
  46109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46110. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46111. __decorate([
  46112. BABYLON.serialize(),
  46113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46114. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46115. __decorate([
  46116. BABYLON.serialize(),
  46117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46118. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46119. __decorate([
  46120. BABYLON.serializeAsTexture(),
  46121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46122. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46123. __decorate([
  46124. BABYLON.serialize(),
  46125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46126. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46127. __decorate([
  46128. BABYLON.serialize(),
  46129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46130. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46131. __decorate([
  46132. BABYLON.serialize(),
  46133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46134. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46135. __decorate([
  46136. BABYLON.serialize(),
  46137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46138. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46139. __decorate([
  46140. BABYLON.serialize(),
  46141. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46142. ], PBRMaterial.prototype, "unlit", void 0);
  46143. return PBRMaterial;
  46144. }(BABYLON.PBRBaseMaterial));
  46145. BABYLON.PBRMaterial = PBRMaterial;
  46146. })(BABYLON || (BABYLON = {}));
  46147. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46148. var BABYLON;
  46149. (function (BABYLON) {
  46150. /**
  46151. * The PBR material of BJS following the metal roughness convention.
  46152. *
  46153. * This fits to the PBR convention in the GLTF definition:
  46154. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46155. */
  46156. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46157. __extends(PBRMetallicRoughnessMaterial, _super);
  46158. /**
  46159. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46160. *
  46161. * @param name The material name
  46162. * @param scene The scene the material will be use in.
  46163. */
  46164. function PBRMetallicRoughnessMaterial(name, scene) {
  46165. var _this = _super.call(this, name, scene) || this;
  46166. _this._useRoughnessFromMetallicTextureAlpha = false;
  46167. _this._useRoughnessFromMetallicTextureGreen = true;
  46168. _this._useMetallnessFromMetallicTextureBlue = true;
  46169. _this.metallic = 1.0;
  46170. _this.roughness = 1.0;
  46171. return _this;
  46172. }
  46173. /**
  46174. * Return the currrent class name of the material.
  46175. */
  46176. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46177. return "PBRMetallicRoughnessMaterial";
  46178. };
  46179. /**
  46180. * Return the active textures of the material.
  46181. */
  46182. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46183. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46184. if (this.baseTexture) {
  46185. activeTextures.push(this.baseTexture);
  46186. }
  46187. if (this.metallicRoughnessTexture) {
  46188. activeTextures.push(this.metallicRoughnessTexture);
  46189. }
  46190. return activeTextures;
  46191. };
  46192. /**
  46193. * Checks to see if a texture is used in the material.
  46194. * @param texture - Base texture to use.
  46195. * @returns - Boolean specifying if a texture is used in the material.
  46196. */
  46197. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46198. if (_super.prototype.hasTexture.call(this, texture)) {
  46199. return true;
  46200. }
  46201. if (this.baseTexture === texture) {
  46202. return true;
  46203. }
  46204. if (this.metallicRoughnessTexture === texture) {
  46205. return true;
  46206. }
  46207. return false;
  46208. };
  46209. /**
  46210. * Makes a duplicate of the current material.
  46211. * @param name - name to use for the new material.
  46212. */
  46213. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46214. var _this = this;
  46215. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46216. clone.id = name;
  46217. clone.name = name;
  46218. return clone;
  46219. };
  46220. /**
  46221. * Serialize the material to a parsable JSON object.
  46222. */
  46223. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46225. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46226. return serializationObject;
  46227. };
  46228. /**
  46229. * Parses a JSON object correponding to the serialize function.
  46230. */
  46231. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46232. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46233. };
  46234. __decorate([
  46235. BABYLON.serializeAsColor3(),
  46236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46237. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46238. __decorate([
  46239. BABYLON.serializeAsTexture(),
  46240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46241. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46242. __decorate([
  46243. BABYLON.serialize(),
  46244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46245. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46246. __decorate([
  46247. BABYLON.serialize(),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46249. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46250. __decorate([
  46251. BABYLON.serializeAsTexture(),
  46252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46253. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46254. return PBRMetallicRoughnessMaterial;
  46255. }(BABYLON.PBRBaseSimpleMaterial));
  46256. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46257. })(BABYLON || (BABYLON = {}));
  46258. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46259. var BABYLON;
  46260. (function (BABYLON) {
  46261. /**
  46262. * The PBR material of BJS following the specular glossiness convention.
  46263. *
  46264. * This fits to the PBR convention in the GLTF definition:
  46265. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46266. */
  46267. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46268. __extends(PBRSpecularGlossinessMaterial, _super);
  46269. /**
  46270. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46271. *
  46272. * @param name The material name
  46273. * @param scene The scene the material will be use in.
  46274. */
  46275. function PBRSpecularGlossinessMaterial(name, scene) {
  46276. var _this = _super.call(this, name, scene) || this;
  46277. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46278. return _this;
  46279. }
  46280. /**
  46281. * Return the currrent class name of the material.
  46282. */
  46283. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46284. return "PBRSpecularGlossinessMaterial";
  46285. };
  46286. /**
  46287. * Return the active textures of the material.
  46288. */
  46289. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46290. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46291. if (this.diffuseTexture) {
  46292. activeTextures.push(this.diffuseTexture);
  46293. }
  46294. if (this.specularGlossinessTexture) {
  46295. activeTextures.push(this.specularGlossinessTexture);
  46296. }
  46297. return activeTextures;
  46298. };
  46299. /**
  46300. * Checks to see if a texture is used in the material.
  46301. * @param texture - Base texture to use.
  46302. * @returns - Boolean specifying if a texture is used in the material.
  46303. */
  46304. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46305. if (_super.prototype.hasTexture.call(this, texture)) {
  46306. return true;
  46307. }
  46308. if (this.diffuseTexture === texture) {
  46309. return true;
  46310. }
  46311. if (this.specularGlossinessTexture === texture) {
  46312. return true;
  46313. }
  46314. return false;
  46315. };
  46316. /**
  46317. * Makes a duplicate of the current material.
  46318. * @param name - name to use for the new material.
  46319. */
  46320. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46321. var _this = this;
  46322. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46323. clone.id = name;
  46324. clone.name = name;
  46325. return clone;
  46326. };
  46327. /**
  46328. * Serialize the material to a parsable JSON object.
  46329. */
  46330. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46331. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46332. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46333. return serializationObject;
  46334. };
  46335. /**
  46336. * Parses a JSON object correponding to the serialize function.
  46337. */
  46338. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46339. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46340. };
  46341. __decorate([
  46342. BABYLON.serializeAsColor3("diffuse"),
  46343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46344. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46345. __decorate([
  46346. BABYLON.serializeAsTexture(),
  46347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46348. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46349. __decorate([
  46350. BABYLON.serializeAsColor3("specular"),
  46351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46352. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46353. __decorate([
  46354. BABYLON.serialize(),
  46355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46356. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46357. __decorate([
  46358. BABYLON.serializeAsTexture(),
  46359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46360. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46361. return PBRSpecularGlossinessMaterial;
  46362. }(BABYLON.PBRBaseSimpleMaterial));
  46363. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46364. })(BABYLON || (BABYLON = {}));
  46365. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46366. var BABYLON;
  46367. (function (BABYLON) {
  46368. BABYLON.CameraInputTypes = {};
  46369. var CameraInputsManager = /** @class */ (function () {
  46370. function CameraInputsManager(camera) {
  46371. this.attached = {};
  46372. this.camera = camera;
  46373. this.checkInputs = function () { };
  46374. }
  46375. /**
  46376. * Add an input method to a camera.
  46377. * builtin inputs example: camera.inputs.addGamepad();
  46378. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46379. * @param input camera input method
  46380. */
  46381. CameraInputsManager.prototype.add = function (input) {
  46382. var type = input.getSimpleName();
  46383. if (this.attached[type]) {
  46384. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46385. return;
  46386. }
  46387. this.attached[type] = input;
  46388. input.camera = this.camera;
  46389. //for checkInputs, we are dynamically creating a function
  46390. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46391. if (input.checkInputs) {
  46392. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46393. }
  46394. if (this.attachedElement) {
  46395. input.attachControl(this.attachedElement);
  46396. }
  46397. };
  46398. /**
  46399. * Remove a specific input method from a camera
  46400. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46401. * @param inputToRemove camera input method
  46402. */
  46403. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46404. for (var cam in this.attached) {
  46405. var input = this.attached[cam];
  46406. if (input === inputToRemove) {
  46407. input.detachControl(this.attachedElement);
  46408. input.camera = null;
  46409. delete this.attached[cam];
  46410. this.rebuildInputCheck();
  46411. }
  46412. }
  46413. };
  46414. CameraInputsManager.prototype.removeByType = function (inputType) {
  46415. for (var cam in this.attached) {
  46416. var input = this.attached[cam];
  46417. if (input.getClassName() === inputType) {
  46418. input.detachControl(this.attachedElement);
  46419. input.camera = null;
  46420. delete this.attached[cam];
  46421. this.rebuildInputCheck();
  46422. }
  46423. }
  46424. };
  46425. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46426. var current = this.checkInputs;
  46427. return function () {
  46428. current();
  46429. fn();
  46430. };
  46431. };
  46432. CameraInputsManager.prototype.attachInput = function (input) {
  46433. if (this.attachedElement) {
  46434. input.attachControl(this.attachedElement, this.noPreventDefault);
  46435. }
  46436. };
  46437. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46438. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46439. if (this.attachedElement) {
  46440. return;
  46441. }
  46442. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46443. this.attachedElement = element;
  46444. this.noPreventDefault = noPreventDefault;
  46445. for (var cam in this.attached) {
  46446. this.attached[cam].attachControl(element, noPreventDefault);
  46447. }
  46448. };
  46449. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46450. if (disconnect === void 0) { disconnect = false; }
  46451. if (this.attachedElement !== element) {
  46452. return;
  46453. }
  46454. for (var cam in this.attached) {
  46455. this.attached[cam].detachControl(element);
  46456. if (disconnect) {
  46457. this.attached[cam].camera = null;
  46458. }
  46459. }
  46460. this.attachedElement = null;
  46461. };
  46462. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46463. this.checkInputs = function () { };
  46464. for (var cam in this.attached) {
  46465. var input = this.attached[cam];
  46466. if (input.checkInputs) {
  46467. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46468. }
  46469. }
  46470. };
  46471. /**
  46472. * Remove all attached input methods from a camera
  46473. */
  46474. CameraInputsManager.prototype.clear = function () {
  46475. if (this.attachedElement) {
  46476. this.detachElement(this.attachedElement, true);
  46477. }
  46478. this.attached = {};
  46479. this.attachedElement = null;
  46480. this.checkInputs = function () { };
  46481. };
  46482. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46483. var inputs = {};
  46484. for (var cam in this.attached) {
  46485. var input = this.attached[cam];
  46486. var res = BABYLON.SerializationHelper.Serialize(input);
  46487. inputs[input.getClassName()] = res;
  46488. }
  46489. serializedCamera.inputsmgr = inputs;
  46490. };
  46491. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46492. var parsedInputs = parsedCamera.inputsmgr;
  46493. if (parsedInputs) {
  46494. this.clear();
  46495. for (var n in parsedInputs) {
  46496. var construct = BABYLON.CameraInputTypes[n];
  46497. if (construct) {
  46498. var parsedinput = parsedInputs[n];
  46499. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46500. this.add(input);
  46501. }
  46502. }
  46503. }
  46504. else {
  46505. //2016-03-08 this part is for managing backward compatibility
  46506. for (var n in this.attached) {
  46507. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46508. if (construct) {
  46509. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46510. this.remove(this.attached[n]);
  46511. this.add(input);
  46512. }
  46513. }
  46514. }
  46515. };
  46516. return CameraInputsManager;
  46517. }());
  46518. BABYLON.CameraInputsManager = CameraInputsManager;
  46519. })(BABYLON || (BABYLON = {}));
  46520. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46521. var BABYLON;
  46522. (function (BABYLON) {
  46523. var TargetCamera = /** @class */ (function (_super) {
  46524. __extends(TargetCamera, _super);
  46525. function TargetCamera(name, position, scene) {
  46526. var _this = _super.call(this, name, position, scene) || this;
  46527. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46528. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46529. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46530. _this.speed = 2.0;
  46531. _this.noRotationConstraint = false;
  46532. _this.lockedTarget = null;
  46533. _this._currentTarget = BABYLON.Vector3.Zero();
  46534. _this._viewMatrix = BABYLON.Matrix.Zero();
  46535. _this._camMatrix = BABYLON.Matrix.Zero();
  46536. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46537. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46538. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46539. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46540. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46541. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46542. _this._tempMatrix = BABYLON.Matrix.Zero();
  46543. return _this;
  46544. }
  46545. TargetCamera.prototype.getFrontPosition = function (distance) {
  46546. this.getWorldMatrix();
  46547. var direction = this.getTarget().subtract(this.position);
  46548. direction.normalize();
  46549. direction.scaleInPlace(distance);
  46550. return this.globalPosition.add(direction);
  46551. };
  46552. TargetCamera.prototype._getLockedTargetPosition = function () {
  46553. if (!this.lockedTarget) {
  46554. return null;
  46555. }
  46556. if (this.lockedTarget.absolutePosition) {
  46557. this.lockedTarget.computeWorldMatrix();
  46558. }
  46559. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46560. };
  46561. TargetCamera.prototype.storeState = function () {
  46562. this._storedPosition = this.position.clone();
  46563. this._storedRotation = this.rotation.clone();
  46564. if (this.rotationQuaternion) {
  46565. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46566. }
  46567. return _super.prototype.storeState.call(this);
  46568. };
  46569. /**
  46570. * Restored camera state. You must call storeState() first
  46571. */
  46572. TargetCamera.prototype._restoreStateValues = function () {
  46573. if (!_super.prototype._restoreStateValues.call(this)) {
  46574. return false;
  46575. }
  46576. this.position = this._storedPosition.clone();
  46577. this.rotation = this._storedRotation.clone();
  46578. if (this.rotationQuaternion) {
  46579. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46580. }
  46581. this.cameraDirection.copyFromFloats(0, 0, 0);
  46582. this.cameraRotation.copyFromFloats(0, 0);
  46583. return true;
  46584. };
  46585. // Cache
  46586. TargetCamera.prototype._initCache = function () {
  46587. _super.prototype._initCache.call(this);
  46588. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46589. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46590. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46591. };
  46592. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46593. if (!ignoreParentClass) {
  46594. _super.prototype._updateCache.call(this);
  46595. }
  46596. var lockedTargetPosition = this._getLockedTargetPosition();
  46597. if (!lockedTargetPosition) {
  46598. this._cache.lockedTarget = null;
  46599. }
  46600. else {
  46601. if (!this._cache.lockedTarget) {
  46602. this._cache.lockedTarget = lockedTargetPosition.clone();
  46603. }
  46604. else {
  46605. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46606. }
  46607. }
  46608. this._cache.rotation.copyFrom(this.rotation);
  46609. if (this.rotationQuaternion)
  46610. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46611. };
  46612. // Synchronized
  46613. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46614. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46615. return false;
  46616. }
  46617. var lockedTargetPosition = this._getLockedTargetPosition();
  46618. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46619. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46620. };
  46621. // Methods
  46622. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46623. var engine = this.getEngine();
  46624. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46625. };
  46626. // Target
  46627. TargetCamera.prototype.setTarget = function (target) {
  46628. this.upVector.normalize();
  46629. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46630. this._camMatrix.invert();
  46631. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46632. var vDir = target.subtract(this.position);
  46633. if (vDir.x >= 0.0) {
  46634. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46635. }
  46636. else {
  46637. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46638. }
  46639. this.rotation.z = 0;
  46640. if (isNaN(this.rotation.x)) {
  46641. this.rotation.x = 0;
  46642. }
  46643. if (isNaN(this.rotation.y)) {
  46644. this.rotation.y = 0;
  46645. }
  46646. if (isNaN(this.rotation.z)) {
  46647. this.rotation.z = 0;
  46648. }
  46649. if (this.rotationQuaternion) {
  46650. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46651. }
  46652. };
  46653. /**
  46654. * Return the current target position of the camera. This value is expressed in local space.
  46655. */
  46656. TargetCamera.prototype.getTarget = function () {
  46657. return this._currentTarget;
  46658. };
  46659. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46660. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46661. };
  46662. TargetCamera.prototype._updatePosition = function () {
  46663. if (this.parent) {
  46664. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46665. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46666. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46667. return;
  46668. }
  46669. this.position.addInPlace(this.cameraDirection);
  46670. };
  46671. TargetCamera.prototype._checkInputs = function () {
  46672. var needToMove = this._decideIfNeedsToMove();
  46673. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46674. // Move
  46675. if (needToMove) {
  46676. this._updatePosition();
  46677. }
  46678. // Rotate
  46679. if (needToRotate) {
  46680. this.rotation.x += this.cameraRotation.x;
  46681. this.rotation.y += this.cameraRotation.y;
  46682. //rotate, if quaternion is set and rotation was used
  46683. if (this.rotationQuaternion) {
  46684. var len = this.rotation.lengthSquared();
  46685. if (len) {
  46686. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46687. }
  46688. }
  46689. if (!this.noRotationConstraint) {
  46690. var limit = (Math.PI / 2) * 0.95;
  46691. if (this.rotation.x > limit)
  46692. this.rotation.x = limit;
  46693. if (this.rotation.x < -limit)
  46694. this.rotation.x = -limit;
  46695. }
  46696. }
  46697. // Inertia
  46698. if (needToMove) {
  46699. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46700. this.cameraDirection.x = 0;
  46701. }
  46702. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46703. this.cameraDirection.y = 0;
  46704. }
  46705. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46706. this.cameraDirection.z = 0;
  46707. }
  46708. this.cameraDirection.scaleInPlace(this.inertia);
  46709. }
  46710. if (needToRotate) {
  46711. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46712. this.cameraRotation.x = 0;
  46713. }
  46714. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46715. this.cameraRotation.y = 0;
  46716. }
  46717. this.cameraRotation.scaleInPlace(this.inertia);
  46718. }
  46719. _super.prototype._checkInputs.call(this);
  46720. };
  46721. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46722. if (this.rotationQuaternion) {
  46723. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46724. }
  46725. else {
  46726. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46727. }
  46728. //update the up vector!
  46729. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46730. };
  46731. TargetCamera.prototype._getViewMatrix = function () {
  46732. if (this.lockedTarget) {
  46733. this.setTarget(this._getLockedTargetPosition());
  46734. }
  46735. // Compute
  46736. this._updateCameraRotationMatrix();
  46737. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46738. // Computing target and final matrix
  46739. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46740. if (this.getScene().useRightHandedSystem) {
  46741. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46742. }
  46743. else {
  46744. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46745. }
  46746. return this._viewMatrix;
  46747. };
  46748. /**
  46749. * @override
  46750. * Override Camera.createRigCamera
  46751. */
  46752. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46753. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46754. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46755. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46756. if (!this.rotationQuaternion) {
  46757. this.rotationQuaternion = new BABYLON.Quaternion();
  46758. }
  46759. rigCamera._cameraRigParams = {};
  46760. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46761. }
  46762. return rigCamera;
  46763. }
  46764. return null;
  46765. };
  46766. /**
  46767. * @override
  46768. * Override Camera._updateRigCameras
  46769. */
  46770. TargetCamera.prototype._updateRigCameras = function () {
  46771. var camLeft = this._rigCameras[0];
  46772. var camRight = this._rigCameras[1];
  46773. switch (this.cameraRigMode) {
  46774. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46775. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46776. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46778. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46779. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46780. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46781. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46782. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46783. camLeft.setTarget(this.getTarget());
  46784. camRight.setTarget(this.getTarget());
  46785. break;
  46786. case BABYLON.Camera.RIG_MODE_VR:
  46787. if (camLeft.rotationQuaternion) {
  46788. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46789. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46790. }
  46791. else {
  46792. camLeft.rotation.copyFrom(this.rotation);
  46793. camRight.rotation.copyFrom(this.rotation);
  46794. }
  46795. camLeft.position.copyFrom(this.position);
  46796. camRight.position.copyFrom(this.position);
  46797. break;
  46798. }
  46799. _super.prototype._updateRigCameras.call(this);
  46800. };
  46801. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46802. if (!this._rigCamTransformMatrix) {
  46803. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46804. }
  46805. var target = this.getTarget();
  46806. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46807. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46808. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46809. };
  46810. TargetCamera.prototype.getClassName = function () {
  46811. return "TargetCamera";
  46812. };
  46813. __decorate([
  46814. BABYLON.serializeAsVector3()
  46815. ], TargetCamera.prototype, "rotation", void 0);
  46816. __decorate([
  46817. BABYLON.serialize()
  46818. ], TargetCamera.prototype, "speed", void 0);
  46819. __decorate([
  46820. BABYLON.serializeAsMeshReference("lockedTargetId")
  46821. ], TargetCamera.prototype, "lockedTarget", void 0);
  46822. return TargetCamera;
  46823. }(BABYLON.Camera));
  46824. BABYLON.TargetCamera = TargetCamera;
  46825. })(BABYLON || (BABYLON = {}));
  46826. //# sourceMappingURL=babylon.targetCamera.js.map
  46827. var BABYLON;
  46828. (function (BABYLON) {
  46829. var FreeCameraMouseInput = /** @class */ (function () {
  46830. function FreeCameraMouseInput(touchEnabled) {
  46831. if (touchEnabled === void 0) { touchEnabled = true; }
  46832. this.touchEnabled = touchEnabled;
  46833. this.buttons = [0, 1, 2];
  46834. this.angularSensibility = 2000.0;
  46835. this.previousPosition = null;
  46836. }
  46837. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46838. var _this = this;
  46839. var engine = this.camera.getEngine();
  46840. if (!this._pointerInput) {
  46841. this._pointerInput = function (p, s) {
  46842. var evt = p.event;
  46843. if (engine.isInVRExclusivePointerMode) {
  46844. return;
  46845. }
  46846. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46847. return;
  46848. }
  46849. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46850. return;
  46851. }
  46852. var srcElement = (evt.srcElement || evt.target);
  46853. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46854. try {
  46855. srcElement.setPointerCapture(evt.pointerId);
  46856. }
  46857. catch (e) {
  46858. //Nothing to do with the error. Execution will continue.
  46859. }
  46860. _this.previousPosition = {
  46861. x: evt.clientX,
  46862. y: evt.clientY
  46863. };
  46864. if (!noPreventDefault) {
  46865. evt.preventDefault();
  46866. element.focus();
  46867. }
  46868. }
  46869. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46870. try {
  46871. srcElement.releasePointerCapture(evt.pointerId);
  46872. }
  46873. catch (e) {
  46874. //Nothing to do with the error.
  46875. }
  46876. _this.previousPosition = null;
  46877. if (!noPreventDefault) {
  46878. evt.preventDefault();
  46879. }
  46880. }
  46881. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46882. if (!_this.previousPosition || engine.isPointerLock) {
  46883. return;
  46884. }
  46885. var offsetX = evt.clientX - _this.previousPosition.x;
  46886. var offsetY = evt.clientY - _this.previousPosition.y;
  46887. if (_this.camera.getScene().useRightHandedSystem) {
  46888. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46889. }
  46890. else {
  46891. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46892. }
  46893. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46894. _this.previousPosition = {
  46895. x: evt.clientX,
  46896. y: evt.clientY
  46897. };
  46898. if (!noPreventDefault) {
  46899. evt.preventDefault();
  46900. }
  46901. }
  46902. };
  46903. }
  46904. this._onMouseMove = function (evt) {
  46905. if (!engine.isPointerLock) {
  46906. return;
  46907. }
  46908. if (engine.isInVRExclusivePointerMode) {
  46909. return;
  46910. }
  46911. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46912. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46913. if (_this.camera.getScene().useRightHandedSystem) {
  46914. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46915. }
  46916. else {
  46917. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46918. }
  46919. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46920. _this.previousPosition = null;
  46921. if (!noPreventDefault) {
  46922. evt.preventDefault();
  46923. }
  46924. };
  46925. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46926. element.addEventListener("mousemove", this._onMouseMove, false);
  46927. };
  46928. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46929. if (this._observer && element) {
  46930. this.camera.getScene().onPointerObservable.remove(this._observer);
  46931. if (this._onMouseMove) {
  46932. element.removeEventListener("mousemove", this._onMouseMove);
  46933. }
  46934. this._observer = null;
  46935. this._onMouseMove = null;
  46936. this.previousPosition = null;
  46937. }
  46938. };
  46939. FreeCameraMouseInput.prototype.getClassName = function () {
  46940. return "FreeCameraMouseInput";
  46941. };
  46942. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46943. return "mouse";
  46944. };
  46945. __decorate([
  46946. BABYLON.serialize()
  46947. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46948. __decorate([
  46949. BABYLON.serialize()
  46950. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46951. return FreeCameraMouseInput;
  46952. }());
  46953. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46954. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46955. })(BABYLON || (BABYLON = {}));
  46956. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46957. var BABYLON;
  46958. (function (BABYLON) {
  46959. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46960. function FreeCameraKeyboardMoveInput() {
  46961. this._keys = new Array();
  46962. this.keysUp = [38];
  46963. this.keysDown = [40];
  46964. this.keysLeft = [37];
  46965. this.keysRight = [39];
  46966. }
  46967. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46968. var _this = this;
  46969. if (this._onCanvasBlurObserver) {
  46970. return;
  46971. }
  46972. this._scene = this.camera.getScene();
  46973. this._engine = this._scene.getEngine();
  46974. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46975. _this._keys = [];
  46976. });
  46977. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46978. var evt = info.event;
  46979. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46980. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46981. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46982. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46983. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46984. var index = _this._keys.indexOf(evt.keyCode);
  46985. if (index === -1) {
  46986. _this._keys.push(evt.keyCode);
  46987. }
  46988. if (!noPreventDefault) {
  46989. evt.preventDefault();
  46990. }
  46991. }
  46992. }
  46993. else {
  46994. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46995. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46996. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46997. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46998. var index = _this._keys.indexOf(evt.keyCode);
  46999. if (index >= 0) {
  47000. _this._keys.splice(index, 1);
  47001. }
  47002. if (!noPreventDefault) {
  47003. evt.preventDefault();
  47004. }
  47005. }
  47006. }
  47007. });
  47008. };
  47009. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47010. if (this._scene) {
  47011. if (this._onKeyboardObserver) {
  47012. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47013. }
  47014. if (this._onCanvasBlurObserver) {
  47015. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47016. }
  47017. this._onKeyboardObserver = null;
  47018. this._onCanvasBlurObserver = null;
  47019. }
  47020. this._keys = [];
  47021. };
  47022. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47023. if (this._onKeyboardObserver) {
  47024. var camera = this.camera;
  47025. // Keyboard
  47026. for (var index = 0; index < this._keys.length; index++) {
  47027. var keyCode = this._keys[index];
  47028. var speed = camera._computeLocalCameraSpeed();
  47029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47030. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47031. }
  47032. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47033. camera._localDirection.copyFromFloats(0, 0, speed);
  47034. }
  47035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47036. camera._localDirection.copyFromFloats(speed, 0, 0);
  47037. }
  47038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47039. camera._localDirection.copyFromFloats(0, 0, -speed);
  47040. }
  47041. if (camera.getScene().useRightHandedSystem) {
  47042. camera._localDirection.z *= -1;
  47043. }
  47044. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47045. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47046. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47047. }
  47048. }
  47049. };
  47050. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47051. return "FreeCameraKeyboardMoveInput";
  47052. };
  47053. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47054. this._keys = [];
  47055. };
  47056. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47057. return "keyboard";
  47058. };
  47059. __decorate([
  47060. BABYLON.serialize()
  47061. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47062. __decorate([
  47063. BABYLON.serialize()
  47064. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47065. __decorate([
  47066. BABYLON.serialize()
  47067. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47068. __decorate([
  47069. BABYLON.serialize()
  47070. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47071. return FreeCameraKeyboardMoveInput;
  47072. }());
  47073. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47074. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47075. })(BABYLON || (BABYLON = {}));
  47076. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47077. var BABYLON;
  47078. (function (BABYLON) {
  47079. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47080. __extends(FreeCameraInputsManager, _super);
  47081. function FreeCameraInputsManager(camera) {
  47082. return _super.call(this, camera) || this;
  47083. }
  47084. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47085. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47086. return this;
  47087. };
  47088. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47089. if (touchEnabled === void 0) { touchEnabled = true; }
  47090. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47091. return this;
  47092. };
  47093. FreeCameraInputsManager.prototype.addGamepad = function () {
  47094. this.add(new BABYLON.FreeCameraGamepadInput());
  47095. return this;
  47096. };
  47097. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47098. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47099. return this;
  47100. };
  47101. FreeCameraInputsManager.prototype.addTouch = function () {
  47102. this.add(new BABYLON.FreeCameraTouchInput());
  47103. return this;
  47104. };
  47105. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47106. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47107. return this;
  47108. };
  47109. return FreeCameraInputsManager;
  47110. }(BABYLON.CameraInputsManager));
  47111. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47112. })(BABYLON || (BABYLON = {}));
  47113. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47114. var BABYLON;
  47115. (function (BABYLON) {
  47116. var FreeCamera = /** @class */ (function (_super) {
  47117. __extends(FreeCamera, _super);
  47118. function FreeCamera(name, position, scene) {
  47119. var _this = _super.call(this, name, position, scene) || this;
  47120. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47121. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47122. _this.checkCollisions = false;
  47123. _this.applyGravity = false;
  47124. _this._needMoveForGravity = false;
  47125. _this._oldPosition = BABYLON.Vector3.Zero();
  47126. _this._diffPosition = BABYLON.Vector3.Zero();
  47127. _this._newPosition = BABYLON.Vector3.Zero();
  47128. // Collisions
  47129. _this._collisionMask = -1;
  47130. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47131. if (collidedMesh === void 0) { collidedMesh = null; }
  47132. //TODO move this to the collision coordinator!
  47133. if (_this.getScene().workerCollisions)
  47134. newPosition.multiplyInPlace(_this._collider._radius);
  47135. var updatePosition = function (newPos) {
  47136. _this._newPosition.copyFrom(newPos);
  47137. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47138. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47139. _this.position.addInPlace(_this._diffPosition);
  47140. if (_this.onCollide && collidedMesh) {
  47141. _this.onCollide(collidedMesh);
  47142. }
  47143. }
  47144. };
  47145. updatePosition(newPosition);
  47146. };
  47147. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47148. _this.inputs.addKeyboard().addMouse();
  47149. return _this;
  47150. }
  47151. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47152. //-- begin properties for backward compatibility for inputs
  47153. /**
  47154. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47155. * Higher values reduce sensitivity.
  47156. */
  47157. get: function () {
  47158. var mouse = this.inputs.attached["mouse"];
  47159. if (mouse)
  47160. return mouse.angularSensibility;
  47161. return 0;
  47162. },
  47163. /**
  47164. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47165. * Higher values reduce sensitivity.
  47166. */
  47167. set: function (value) {
  47168. var mouse = this.inputs.attached["mouse"];
  47169. if (mouse)
  47170. mouse.angularSensibility = value;
  47171. },
  47172. enumerable: true,
  47173. configurable: true
  47174. });
  47175. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47176. get: function () {
  47177. var keyboard = this.inputs.attached["keyboard"];
  47178. if (keyboard)
  47179. return keyboard.keysUp;
  47180. return [];
  47181. },
  47182. set: function (value) {
  47183. var keyboard = this.inputs.attached["keyboard"];
  47184. if (keyboard)
  47185. keyboard.keysUp = value;
  47186. },
  47187. enumerable: true,
  47188. configurable: true
  47189. });
  47190. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47191. get: function () {
  47192. var keyboard = this.inputs.attached["keyboard"];
  47193. if (keyboard)
  47194. return keyboard.keysDown;
  47195. return [];
  47196. },
  47197. set: function (value) {
  47198. var keyboard = this.inputs.attached["keyboard"];
  47199. if (keyboard)
  47200. keyboard.keysDown = value;
  47201. },
  47202. enumerable: true,
  47203. configurable: true
  47204. });
  47205. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47206. get: function () {
  47207. var keyboard = this.inputs.attached["keyboard"];
  47208. if (keyboard)
  47209. return keyboard.keysLeft;
  47210. return [];
  47211. },
  47212. set: function (value) {
  47213. var keyboard = this.inputs.attached["keyboard"];
  47214. if (keyboard)
  47215. keyboard.keysLeft = value;
  47216. },
  47217. enumerable: true,
  47218. configurable: true
  47219. });
  47220. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47221. get: function () {
  47222. var keyboard = this.inputs.attached["keyboard"];
  47223. if (keyboard)
  47224. return keyboard.keysRight;
  47225. return [];
  47226. },
  47227. set: function (value) {
  47228. var keyboard = this.inputs.attached["keyboard"];
  47229. if (keyboard)
  47230. keyboard.keysRight = value;
  47231. },
  47232. enumerable: true,
  47233. configurable: true
  47234. });
  47235. // Controls
  47236. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47237. this.inputs.attachElement(element, noPreventDefault);
  47238. };
  47239. FreeCamera.prototype.detachControl = function (element) {
  47240. this.inputs.detachElement(element);
  47241. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47242. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47243. };
  47244. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47245. get: function () {
  47246. return this._collisionMask;
  47247. },
  47248. set: function (mask) {
  47249. this._collisionMask = !isNaN(mask) ? mask : -1;
  47250. },
  47251. enumerable: true,
  47252. configurable: true
  47253. });
  47254. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47255. var globalPosition;
  47256. if (this.parent) {
  47257. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47258. }
  47259. else {
  47260. globalPosition = this.position;
  47261. }
  47262. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47263. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47264. if (!this._collider) {
  47265. this._collider = new BABYLON.Collider();
  47266. }
  47267. this._collider._radius = this.ellipsoid;
  47268. this._collider.collisionMask = this._collisionMask;
  47269. //no need for clone, as long as gravity is not on.
  47270. var actualDisplacement = displacement;
  47271. //add gravity to the direction to prevent the dual-collision checking
  47272. if (this.applyGravity) {
  47273. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47274. actualDisplacement = displacement.add(this.getScene().gravity);
  47275. }
  47276. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47277. };
  47278. FreeCamera.prototype._checkInputs = function () {
  47279. if (!this._localDirection) {
  47280. this._localDirection = BABYLON.Vector3.Zero();
  47281. this._transformedDirection = BABYLON.Vector3.Zero();
  47282. }
  47283. this.inputs.checkInputs();
  47284. _super.prototype._checkInputs.call(this);
  47285. };
  47286. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47287. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47288. };
  47289. FreeCamera.prototype._updatePosition = function () {
  47290. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47291. this._collideWithWorld(this.cameraDirection);
  47292. }
  47293. else {
  47294. _super.prototype._updatePosition.call(this);
  47295. }
  47296. };
  47297. FreeCamera.prototype.dispose = function () {
  47298. this.inputs.clear();
  47299. _super.prototype.dispose.call(this);
  47300. };
  47301. FreeCamera.prototype.getClassName = function () {
  47302. return "FreeCamera";
  47303. };
  47304. __decorate([
  47305. BABYLON.serializeAsVector3()
  47306. ], FreeCamera.prototype, "ellipsoid", void 0);
  47307. __decorate([
  47308. BABYLON.serializeAsVector3()
  47309. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47310. __decorate([
  47311. BABYLON.serialize()
  47312. ], FreeCamera.prototype, "checkCollisions", void 0);
  47313. __decorate([
  47314. BABYLON.serialize()
  47315. ], FreeCamera.prototype, "applyGravity", void 0);
  47316. return FreeCamera;
  47317. }(BABYLON.TargetCamera));
  47318. BABYLON.FreeCamera = FreeCamera;
  47319. })(BABYLON || (BABYLON = {}));
  47320. //# sourceMappingURL=babylon.freeCamera.js.map
  47321. var BABYLON;
  47322. (function (BABYLON) {
  47323. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47324. function ArcRotateCameraKeyboardMoveInput() {
  47325. this._keys = new Array();
  47326. this.keysUp = [38];
  47327. this.keysDown = [40];
  47328. this.keysLeft = [37];
  47329. this.keysRight = [39];
  47330. this.keysReset = [220];
  47331. this.panningSensibility = 50.0;
  47332. this.zoomingSensibility = 25.0;
  47333. this.useAltToZoom = true;
  47334. }
  47335. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47336. var _this = this;
  47337. if (this._onCanvasBlurObserver) {
  47338. return;
  47339. }
  47340. this._scene = this.camera.getScene();
  47341. this._engine = this._scene.getEngine();
  47342. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47343. _this._keys = [];
  47344. });
  47345. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47346. var evt = info.event;
  47347. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47348. _this._ctrlPressed = evt.ctrlKey;
  47349. _this._altPressed = evt.altKey;
  47350. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47351. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47352. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47353. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47354. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47355. var index = _this._keys.indexOf(evt.keyCode);
  47356. if (index === -1) {
  47357. _this._keys.push(evt.keyCode);
  47358. }
  47359. if (evt.preventDefault) {
  47360. if (!noPreventDefault) {
  47361. evt.preventDefault();
  47362. }
  47363. }
  47364. }
  47365. }
  47366. else {
  47367. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47368. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47369. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47370. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47371. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47372. var index = _this._keys.indexOf(evt.keyCode);
  47373. if (index >= 0) {
  47374. _this._keys.splice(index, 1);
  47375. }
  47376. if (evt.preventDefault) {
  47377. if (!noPreventDefault) {
  47378. evt.preventDefault();
  47379. }
  47380. }
  47381. }
  47382. }
  47383. });
  47384. };
  47385. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47386. if (this._scene) {
  47387. if (this._onKeyboardObserver) {
  47388. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47389. }
  47390. if (this._onCanvasBlurObserver) {
  47391. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47392. }
  47393. this._onKeyboardObserver = null;
  47394. this._onCanvasBlurObserver = null;
  47395. }
  47396. this._keys = [];
  47397. };
  47398. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47399. if (this._onKeyboardObserver) {
  47400. var camera = this.camera;
  47401. for (var index = 0; index < this._keys.length; index++) {
  47402. var keyCode = this._keys[index];
  47403. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47404. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47405. camera.inertialPanningX -= 1 / this.panningSensibility;
  47406. }
  47407. else {
  47408. camera.inertialAlphaOffset -= 0.01;
  47409. }
  47410. }
  47411. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47412. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47413. camera.inertialPanningY += 1 / this.panningSensibility;
  47414. }
  47415. else if (this._altPressed && this.useAltToZoom) {
  47416. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47417. }
  47418. else {
  47419. camera.inertialBetaOffset -= 0.01;
  47420. }
  47421. }
  47422. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47423. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47424. camera.inertialPanningX += 1 / this.panningSensibility;
  47425. }
  47426. else {
  47427. camera.inertialAlphaOffset += 0.01;
  47428. }
  47429. }
  47430. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47431. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47432. camera.inertialPanningY -= 1 / this.panningSensibility;
  47433. }
  47434. else if (this._altPressed && this.useAltToZoom) {
  47435. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47436. }
  47437. else {
  47438. camera.inertialBetaOffset += 0.01;
  47439. }
  47440. }
  47441. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47442. camera.restoreState();
  47443. }
  47444. }
  47445. }
  47446. };
  47447. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47448. return "ArcRotateCameraKeyboardMoveInput";
  47449. };
  47450. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47451. return "keyboard";
  47452. };
  47453. __decorate([
  47454. BABYLON.serialize()
  47455. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47456. __decorate([
  47457. BABYLON.serialize()
  47458. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47459. __decorate([
  47460. BABYLON.serialize()
  47461. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47462. __decorate([
  47463. BABYLON.serialize()
  47464. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47465. __decorate([
  47466. BABYLON.serialize()
  47467. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47468. __decorate([
  47469. BABYLON.serialize()
  47470. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47471. __decorate([
  47472. BABYLON.serialize()
  47473. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47474. __decorate([
  47475. BABYLON.serialize()
  47476. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47477. return ArcRotateCameraKeyboardMoveInput;
  47478. }());
  47479. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47480. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47481. })(BABYLON || (BABYLON = {}));
  47482. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47483. var BABYLON;
  47484. (function (BABYLON) {
  47485. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47486. function ArcRotateCameraMouseWheelInput() {
  47487. this.wheelPrecision = 3.0;
  47488. /**
  47489. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47490. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47491. */
  47492. this.wheelDeltaPercentage = 0;
  47493. }
  47494. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47495. var _this = this;
  47496. this._wheel = function (p, s) {
  47497. //sanity check - this should be a PointerWheel event.
  47498. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47499. return;
  47500. var event = p.event;
  47501. var delta = 0;
  47502. if (event.wheelDelta) {
  47503. if (_this.wheelDeltaPercentage) {
  47504. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47505. if (event.wheelDelta > 0) {
  47506. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47507. }
  47508. else {
  47509. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47510. }
  47511. }
  47512. else {
  47513. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47514. }
  47515. }
  47516. else if (event.detail) {
  47517. delta = -event.detail / _this.wheelPrecision;
  47518. }
  47519. if (delta)
  47520. _this.camera.inertialRadiusOffset += delta;
  47521. if (event.preventDefault) {
  47522. if (!noPreventDefault) {
  47523. event.preventDefault();
  47524. }
  47525. }
  47526. };
  47527. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47528. };
  47529. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47530. if (this._observer && element) {
  47531. this.camera.getScene().onPointerObservable.remove(this._observer);
  47532. this._observer = null;
  47533. this._wheel = null;
  47534. }
  47535. };
  47536. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47537. return "ArcRotateCameraMouseWheelInput";
  47538. };
  47539. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47540. return "mousewheel";
  47541. };
  47542. __decorate([
  47543. BABYLON.serialize()
  47544. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47545. __decorate([
  47546. BABYLON.serialize()
  47547. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47548. return ArcRotateCameraMouseWheelInput;
  47549. }());
  47550. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47551. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47552. })(BABYLON || (BABYLON = {}));
  47553. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47554. var BABYLON;
  47555. (function (BABYLON) {
  47556. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47557. function ArcRotateCameraPointersInput() {
  47558. this.buttons = [0, 1, 2];
  47559. this.angularSensibilityX = 1000.0;
  47560. this.angularSensibilityY = 1000.0;
  47561. this.pinchPrecision = 12.0;
  47562. /**
  47563. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47564. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47565. */
  47566. this.pinchDeltaPercentage = 0;
  47567. this.panningSensibility = 1000.0;
  47568. this.multiTouchPanning = true;
  47569. this.multiTouchPanAndZoom = true;
  47570. this._isPanClick = false;
  47571. this.pinchInwards = true;
  47572. }
  47573. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47574. var _this = this;
  47575. var engine = this.camera.getEngine();
  47576. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47577. var pointA = null;
  47578. var pointB = null;
  47579. var previousPinchSquaredDistance = 0;
  47580. var initialDistance = 0;
  47581. var twoFingerActivityCount = 0;
  47582. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47583. this._pointerInput = function (p, s) {
  47584. var evt = p.event;
  47585. var isTouch = p.event.pointerType === "touch";
  47586. if (engine.isInVRExclusivePointerMode) {
  47587. return;
  47588. }
  47589. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47590. return;
  47591. }
  47592. var srcElement = (evt.srcElement || evt.target);
  47593. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47594. try {
  47595. srcElement.setPointerCapture(evt.pointerId);
  47596. }
  47597. catch (e) {
  47598. //Nothing to do with the error. Execution will continue.
  47599. }
  47600. // Manage panning with pan button click
  47601. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47602. // manage pointers
  47603. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47604. if (pointA === null) {
  47605. pointA = cacheSoloPointer;
  47606. }
  47607. else if (pointB === null) {
  47608. pointB = cacheSoloPointer;
  47609. }
  47610. if (!noPreventDefault) {
  47611. evt.preventDefault();
  47612. element.focus();
  47613. }
  47614. }
  47615. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47616. _this.camera.restoreState();
  47617. }
  47618. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47619. try {
  47620. srcElement.releasePointerCapture(evt.pointerId);
  47621. }
  47622. catch (e) {
  47623. //Nothing to do with the error.
  47624. }
  47625. cacheSoloPointer = null;
  47626. previousPinchSquaredDistance = 0;
  47627. previousMultiTouchPanPosition.isPaning = false;
  47628. previousMultiTouchPanPosition.isPinching = false;
  47629. twoFingerActivityCount = 0;
  47630. initialDistance = 0;
  47631. if (!isTouch) {
  47632. pointB = null; // Mouse and pen are mono pointer
  47633. }
  47634. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47635. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47636. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47637. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47638. if (engine._badOS) {
  47639. pointA = pointB = null;
  47640. }
  47641. else {
  47642. //only remove the impacted pointer in case of multitouch allowing on most
  47643. //platforms switching from rotate to zoom and pan seamlessly.
  47644. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47645. pointA = pointB;
  47646. pointB = null;
  47647. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47648. }
  47649. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47650. pointB = null;
  47651. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47652. }
  47653. else {
  47654. pointA = pointB = null;
  47655. }
  47656. }
  47657. if (!noPreventDefault) {
  47658. evt.preventDefault();
  47659. }
  47660. }
  47661. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47662. if (!noPreventDefault) {
  47663. evt.preventDefault();
  47664. }
  47665. // One button down
  47666. if (pointA && pointB === null && cacheSoloPointer) {
  47667. if (_this.panningSensibility !== 0 &&
  47668. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47669. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47670. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47671. }
  47672. else {
  47673. var offsetX = evt.clientX - cacheSoloPointer.x;
  47674. var offsetY = evt.clientY - cacheSoloPointer.y;
  47675. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47676. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47677. }
  47678. cacheSoloPointer.x = evt.clientX;
  47679. cacheSoloPointer.y = evt.clientY;
  47680. }
  47681. // Two buttons down: pinch/pan
  47682. else if (pointA && pointB) {
  47683. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47684. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47685. ed.x = evt.clientX;
  47686. ed.y = evt.clientY;
  47687. var direction = _this.pinchInwards ? 1 : -1;
  47688. var distX = pointA.x - pointB.x;
  47689. var distY = pointA.y - pointB.y;
  47690. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47691. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47692. if (previousPinchSquaredDistance === 0) {
  47693. initialDistance = pinchDistance;
  47694. previousPinchSquaredDistance = pinchSquaredDistance;
  47695. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47696. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47697. return;
  47698. }
  47699. if (_this.multiTouchPanAndZoom) {
  47700. if (_this.pinchDeltaPercentage) {
  47701. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47702. }
  47703. else {
  47704. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47705. (_this.pinchPrecision *
  47706. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47707. direction);
  47708. }
  47709. if (_this.panningSensibility !== 0) {
  47710. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47711. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47712. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47713. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47714. previousMultiTouchPanPosition.x = pointersCenterX;
  47715. previousMultiTouchPanPosition.y = pointersCenterY;
  47716. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47717. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47718. }
  47719. }
  47720. else {
  47721. twoFingerActivityCount++;
  47722. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47723. if (_this.pinchDeltaPercentage) {
  47724. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47725. }
  47726. else {
  47727. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47728. (_this.pinchPrecision *
  47729. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47730. direction);
  47731. }
  47732. previousMultiTouchPanPosition.isPaning = false;
  47733. previousMultiTouchPanPosition.isPinching = true;
  47734. }
  47735. else {
  47736. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47737. if (!previousMultiTouchPanPosition.isPaning) {
  47738. previousMultiTouchPanPosition.isPaning = true;
  47739. previousMultiTouchPanPosition.isPinching = false;
  47740. previousMultiTouchPanPosition.x = ed.x;
  47741. previousMultiTouchPanPosition.y = ed.y;
  47742. return;
  47743. }
  47744. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47745. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47746. }
  47747. }
  47748. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47749. previousMultiTouchPanPosition.x = ed.x;
  47750. previousMultiTouchPanPosition.y = ed.y;
  47751. }
  47752. }
  47753. previousPinchSquaredDistance = pinchSquaredDistance;
  47754. }
  47755. }
  47756. };
  47757. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47758. this._onContextMenu = function (evt) {
  47759. evt.preventDefault();
  47760. };
  47761. if (!this.camera._useCtrlForPanning) {
  47762. element.addEventListener("contextmenu", this._onContextMenu, false);
  47763. }
  47764. this._onLostFocus = function () {
  47765. //this._keys = [];
  47766. pointA = pointB = null;
  47767. previousPinchSquaredDistance = 0;
  47768. previousMultiTouchPanPosition.isPaning = false;
  47769. previousMultiTouchPanPosition.isPinching = false;
  47770. twoFingerActivityCount = 0;
  47771. cacheSoloPointer = null;
  47772. initialDistance = 0;
  47773. };
  47774. this._onMouseMove = function (evt) {
  47775. if (!engine.isPointerLock) {
  47776. return;
  47777. }
  47778. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47779. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47780. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47781. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47782. if (!noPreventDefault) {
  47783. evt.preventDefault();
  47784. }
  47785. };
  47786. this._onGestureStart = function (e) {
  47787. if (window.MSGesture === undefined) {
  47788. return;
  47789. }
  47790. if (!_this._MSGestureHandler) {
  47791. _this._MSGestureHandler = new MSGesture();
  47792. _this._MSGestureHandler.target = element;
  47793. }
  47794. _this._MSGestureHandler.addPointer(e.pointerId);
  47795. };
  47796. this._onGesture = function (e) {
  47797. _this.camera.radius *= e.scale;
  47798. if (e.preventDefault) {
  47799. if (!noPreventDefault) {
  47800. e.stopPropagation();
  47801. e.preventDefault();
  47802. }
  47803. }
  47804. };
  47805. element.addEventListener("mousemove", this._onMouseMove, false);
  47806. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47807. element.addEventListener("MSGestureChange", this._onGesture, false);
  47808. BABYLON.Tools.RegisterTopRootEvents([
  47809. { name: "blur", handler: this._onLostFocus }
  47810. ]);
  47811. };
  47812. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47813. if (this._onLostFocus) {
  47814. BABYLON.Tools.UnregisterTopRootEvents([
  47815. { name: "blur", handler: this._onLostFocus }
  47816. ]);
  47817. }
  47818. if (element && this._observer) {
  47819. this.camera.getScene().onPointerObservable.remove(this._observer);
  47820. this._observer = null;
  47821. if (this._onContextMenu) {
  47822. element.removeEventListener("contextmenu", this._onContextMenu);
  47823. }
  47824. if (this._onMouseMove) {
  47825. element.removeEventListener("mousemove", this._onMouseMove);
  47826. }
  47827. if (this._onGestureStart) {
  47828. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47829. }
  47830. if (this._onGesture) {
  47831. element.removeEventListener("MSGestureChange", this._onGesture);
  47832. }
  47833. this._isPanClick = false;
  47834. this.pinchInwards = true;
  47835. this._onMouseMove = null;
  47836. this._onGestureStart = null;
  47837. this._onGesture = null;
  47838. this._MSGestureHandler = null;
  47839. this._onLostFocus = null;
  47840. this._onContextMenu = null;
  47841. }
  47842. };
  47843. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47844. return "ArcRotateCameraPointersInput";
  47845. };
  47846. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47847. return "pointers";
  47848. };
  47849. __decorate([
  47850. BABYLON.serialize()
  47851. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47852. __decorate([
  47853. BABYLON.serialize()
  47854. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47855. __decorate([
  47856. BABYLON.serialize()
  47857. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47858. __decorate([
  47859. BABYLON.serialize()
  47860. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47861. __decorate([
  47862. BABYLON.serialize()
  47863. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47864. __decorate([
  47865. BABYLON.serialize()
  47866. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47867. __decorate([
  47868. BABYLON.serialize()
  47869. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47873. return ArcRotateCameraPointersInput;
  47874. }());
  47875. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47876. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47877. })(BABYLON || (BABYLON = {}));
  47878. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47879. var BABYLON;
  47880. (function (BABYLON) {
  47881. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47882. __extends(ArcRotateCameraInputsManager, _super);
  47883. function ArcRotateCameraInputsManager(camera) {
  47884. return _super.call(this, camera) || this;
  47885. }
  47886. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47887. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47888. return this;
  47889. };
  47890. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47891. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47892. return this;
  47893. };
  47894. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47895. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47896. return this;
  47897. };
  47898. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47899. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47900. return this;
  47901. };
  47902. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47903. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47904. return this;
  47905. };
  47906. return ArcRotateCameraInputsManager;
  47907. }(BABYLON.CameraInputsManager));
  47908. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47909. })(BABYLON || (BABYLON = {}));
  47910. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47911. var BABYLON;
  47912. (function (BABYLON) {
  47913. var ArcRotateCamera = /** @class */ (function (_super) {
  47914. __extends(ArcRotateCamera, _super);
  47915. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47916. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47917. _this.inertialAlphaOffset = 0;
  47918. _this.inertialBetaOffset = 0;
  47919. _this.inertialRadiusOffset = 0;
  47920. _this.lowerAlphaLimit = null;
  47921. _this.upperAlphaLimit = null;
  47922. _this.lowerBetaLimit = 0.01;
  47923. _this.upperBetaLimit = Math.PI;
  47924. _this.lowerRadiusLimit = null;
  47925. _this.upperRadiusLimit = null;
  47926. _this.inertialPanningX = 0;
  47927. _this.inertialPanningY = 0;
  47928. _this.pinchToPanMaxDistance = 20;
  47929. _this.panningDistanceLimit = null;
  47930. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47931. _this.panningInertia = 0.9;
  47932. //-- end properties for backward compatibility for inputs
  47933. _this.zoomOnFactor = 1;
  47934. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47935. _this.allowUpsideDown = true;
  47936. _this._viewMatrix = new BABYLON.Matrix();
  47937. // Panning
  47938. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47939. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47940. _this.checkCollisions = false;
  47941. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47942. _this._previousPosition = BABYLON.Vector3.Zero();
  47943. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47944. _this._newPosition = BABYLON.Vector3.Zero();
  47945. _this._computationVector = BABYLON.Vector3.Zero();
  47946. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47947. if (collidedMesh === void 0) { collidedMesh = null; }
  47948. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47949. newPosition.multiplyInPlace(_this._collider._radius);
  47950. }
  47951. if (!collidedMesh) {
  47952. _this._previousPosition.copyFrom(_this.position);
  47953. }
  47954. else {
  47955. _this.setPosition(newPosition);
  47956. if (_this.onCollide) {
  47957. _this.onCollide(collidedMesh);
  47958. }
  47959. }
  47960. // Recompute because of constraints
  47961. var cosa = Math.cos(_this.alpha);
  47962. var sina = Math.sin(_this.alpha);
  47963. var cosb = Math.cos(_this.beta);
  47964. var sinb = Math.sin(_this.beta);
  47965. if (sinb === 0) {
  47966. sinb = 0.0001;
  47967. }
  47968. var target = _this._getTargetPosition();
  47969. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47970. target.addToRef(_this._computationVector, _this._newPosition);
  47971. _this.position.copyFrom(_this._newPosition);
  47972. var up = _this.upVector;
  47973. if (_this.allowUpsideDown && _this.beta < 0) {
  47974. up = up.clone();
  47975. up = up.negate();
  47976. }
  47977. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47978. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47979. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47980. _this._collisionTriggered = false;
  47981. };
  47982. _this._target = BABYLON.Vector3.Zero();
  47983. if (target) {
  47984. _this.setTarget(target);
  47985. }
  47986. _this.alpha = alpha;
  47987. _this.beta = beta;
  47988. _this.radius = radius;
  47989. _this.getViewMatrix();
  47990. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47991. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47992. return _this;
  47993. }
  47994. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47995. get: function () {
  47996. return this._target;
  47997. },
  47998. set: function (value) {
  47999. this.setTarget(value);
  48000. },
  48001. enumerable: true,
  48002. configurable: true
  48003. });
  48004. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48005. //-- begin properties for backward compatibility for inputs
  48006. get: function () {
  48007. var pointers = this.inputs.attached["pointers"];
  48008. if (pointers)
  48009. return pointers.angularSensibilityX;
  48010. return 0;
  48011. },
  48012. set: function (value) {
  48013. var pointers = this.inputs.attached["pointers"];
  48014. if (pointers) {
  48015. pointers.angularSensibilityX = value;
  48016. }
  48017. },
  48018. enumerable: true,
  48019. configurable: true
  48020. });
  48021. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48022. get: function () {
  48023. var pointers = this.inputs.attached["pointers"];
  48024. if (pointers)
  48025. return pointers.angularSensibilityY;
  48026. return 0;
  48027. },
  48028. set: function (value) {
  48029. var pointers = this.inputs.attached["pointers"];
  48030. if (pointers) {
  48031. pointers.angularSensibilityY = value;
  48032. }
  48033. },
  48034. enumerable: true,
  48035. configurable: true
  48036. });
  48037. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48038. get: function () {
  48039. var pointers = this.inputs.attached["pointers"];
  48040. if (pointers)
  48041. return pointers.pinchPrecision;
  48042. return 0;
  48043. },
  48044. set: function (value) {
  48045. var pointers = this.inputs.attached["pointers"];
  48046. if (pointers) {
  48047. pointers.pinchPrecision = value;
  48048. }
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48054. get: function () {
  48055. var pointers = this.inputs.attached["pointers"];
  48056. if (pointers)
  48057. return pointers.pinchDeltaPercentage;
  48058. return 0;
  48059. },
  48060. set: function (value) {
  48061. var pointers = this.inputs.attached["pointers"];
  48062. if (pointers) {
  48063. pointers.pinchDeltaPercentage = value;
  48064. }
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48070. get: function () {
  48071. var pointers = this.inputs.attached["pointers"];
  48072. if (pointers)
  48073. return pointers.panningSensibility;
  48074. return 0;
  48075. },
  48076. set: function (value) {
  48077. var pointers = this.inputs.attached["pointers"];
  48078. if (pointers) {
  48079. pointers.panningSensibility = value;
  48080. }
  48081. },
  48082. enumerable: true,
  48083. configurable: true
  48084. });
  48085. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48086. get: function () {
  48087. var keyboard = this.inputs.attached["keyboard"];
  48088. if (keyboard)
  48089. return keyboard.keysUp;
  48090. return [];
  48091. },
  48092. set: function (value) {
  48093. var keyboard = this.inputs.attached["keyboard"];
  48094. if (keyboard)
  48095. keyboard.keysUp = value;
  48096. },
  48097. enumerable: true,
  48098. configurable: true
  48099. });
  48100. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48101. get: function () {
  48102. var keyboard = this.inputs.attached["keyboard"];
  48103. if (keyboard)
  48104. return keyboard.keysDown;
  48105. return [];
  48106. },
  48107. set: function (value) {
  48108. var keyboard = this.inputs.attached["keyboard"];
  48109. if (keyboard)
  48110. keyboard.keysDown = value;
  48111. },
  48112. enumerable: true,
  48113. configurable: true
  48114. });
  48115. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48116. get: function () {
  48117. var keyboard = this.inputs.attached["keyboard"];
  48118. if (keyboard)
  48119. return keyboard.keysLeft;
  48120. return [];
  48121. },
  48122. set: function (value) {
  48123. var keyboard = this.inputs.attached["keyboard"];
  48124. if (keyboard)
  48125. keyboard.keysLeft = value;
  48126. },
  48127. enumerable: true,
  48128. configurable: true
  48129. });
  48130. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48131. get: function () {
  48132. var keyboard = this.inputs.attached["keyboard"];
  48133. if (keyboard)
  48134. return keyboard.keysRight;
  48135. return [];
  48136. },
  48137. set: function (value) {
  48138. var keyboard = this.inputs.attached["keyboard"];
  48139. if (keyboard)
  48140. keyboard.keysRight = value;
  48141. },
  48142. enumerable: true,
  48143. configurable: true
  48144. });
  48145. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48146. get: function () {
  48147. var mousewheel = this.inputs.attached["mousewheel"];
  48148. if (mousewheel)
  48149. return mousewheel.wheelPrecision;
  48150. return 0;
  48151. },
  48152. set: function (value) {
  48153. var mousewheel = this.inputs.attached["mousewheel"];
  48154. if (mousewheel)
  48155. mousewheel.wheelPrecision = value;
  48156. },
  48157. enumerable: true,
  48158. configurable: true
  48159. });
  48160. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48161. get: function () {
  48162. var mousewheel = this.inputs.attached["mousewheel"];
  48163. if (mousewheel)
  48164. return mousewheel.wheelDeltaPercentage;
  48165. return 0;
  48166. },
  48167. set: function (value) {
  48168. var mousewheel = this.inputs.attached["mousewheel"];
  48169. if (mousewheel)
  48170. mousewheel.wheelDeltaPercentage = value;
  48171. },
  48172. enumerable: true,
  48173. configurable: true
  48174. });
  48175. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48176. get: function () {
  48177. return this._bouncingBehavior;
  48178. },
  48179. enumerable: true,
  48180. configurable: true
  48181. });
  48182. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48183. get: function () {
  48184. return this._bouncingBehavior != null;
  48185. },
  48186. set: function (value) {
  48187. if (value === this.useBouncingBehavior) {
  48188. return;
  48189. }
  48190. if (value) {
  48191. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48192. this.addBehavior(this._bouncingBehavior);
  48193. }
  48194. else if (this._bouncingBehavior) {
  48195. this.removeBehavior(this._bouncingBehavior);
  48196. this._bouncingBehavior = null;
  48197. }
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48203. get: function () {
  48204. return this._framingBehavior;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48210. get: function () {
  48211. return this._framingBehavior != null;
  48212. },
  48213. set: function (value) {
  48214. if (value === this.useFramingBehavior) {
  48215. return;
  48216. }
  48217. if (value) {
  48218. this._framingBehavior = new BABYLON.FramingBehavior();
  48219. this.addBehavior(this._framingBehavior);
  48220. }
  48221. else if (this._framingBehavior) {
  48222. this.removeBehavior(this._framingBehavior);
  48223. this._framingBehavior = null;
  48224. }
  48225. },
  48226. enumerable: true,
  48227. configurable: true
  48228. });
  48229. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48230. get: function () {
  48231. return this._autoRotationBehavior;
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48237. get: function () {
  48238. return this._autoRotationBehavior != null;
  48239. },
  48240. set: function (value) {
  48241. if (value === this.useAutoRotationBehavior) {
  48242. return;
  48243. }
  48244. if (value) {
  48245. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48246. this.addBehavior(this._autoRotationBehavior);
  48247. }
  48248. else if (this._autoRotationBehavior) {
  48249. this.removeBehavior(this._autoRotationBehavior);
  48250. this._autoRotationBehavior = null;
  48251. }
  48252. },
  48253. enumerable: true,
  48254. configurable: true
  48255. });
  48256. // Cache
  48257. ArcRotateCamera.prototype._initCache = function () {
  48258. _super.prototype._initCache.call(this);
  48259. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48260. this._cache.alpha = undefined;
  48261. this._cache.beta = undefined;
  48262. this._cache.radius = undefined;
  48263. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48264. };
  48265. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48266. if (!ignoreParentClass) {
  48267. _super.prototype._updateCache.call(this);
  48268. }
  48269. this._cache._target.copyFrom(this._getTargetPosition());
  48270. this._cache.alpha = this.alpha;
  48271. this._cache.beta = this.beta;
  48272. this._cache.radius = this.radius;
  48273. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48274. };
  48275. ArcRotateCamera.prototype._getTargetPosition = function () {
  48276. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48277. var pos = this._targetHost.getAbsolutePosition();
  48278. if (this._targetBoundingCenter) {
  48279. pos.addToRef(this._targetBoundingCenter, this._target);
  48280. }
  48281. else {
  48282. this._target.copyFrom(pos);
  48283. }
  48284. }
  48285. var lockedTargetPosition = this._getLockedTargetPosition();
  48286. if (lockedTargetPosition) {
  48287. return lockedTargetPosition;
  48288. }
  48289. return this._target;
  48290. };
  48291. ArcRotateCamera.prototype.storeState = function () {
  48292. this._storedAlpha = this.alpha;
  48293. this._storedBeta = this.beta;
  48294. this._storedRadius = this.radius;
  48295. this._storedTarget = this._getTargetPosition().clone();
  48296. return _super.prototype.storeState.call(this);
  48297. };
  48298. /**
  48299. * Restored camera state. You must call storeState() first
  48300. */
  48301. ArcRotateCamera.prototype._restoreStateValues = function () {
  48302. if (!_super.prototype._restoreStateValues.call(this)) {
  48303. return false;
  48304. }
  48305. this.alpha = this._storedAlpha;
  48306. this.beta = this._storedBeta;
  48307. this.radius = this._storedRadius;
  48308. this.setTarget(this._storedTarget.clone());
  48309. this.inertialAlphaOffset = 0;
  48310. this.inertialBetaOffset = 0;
  48311. this.inertialRadiusOffset = 0;
  48312. this.inertialPanningX = 0;
  48313. this.inertialPanningY = 0;
  48314. return true;
  48315. };
  48316. // Synchronized
  48317. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48318. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48319. return false;
  48320. return this._cache._target.equals(this._getTargetPosition())
  48321. && this._cache.alpha === this.alpha
  48322. && this._cache.beta === this.beta
  48323. && this._cache.radius === this.radius
  48324. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48325. };
  48326. // Methods
  48327. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48328. var _this = this;
  48329. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48330. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48331. this._useCtrlForPanning = useCtrlForPanning;
  48332. this._panningMouseButton = panningMouseButton;
  48333. this.inputs.attachElement(element, noPreventDefault);
  48334. this._reset = function () {
  48335. _this.inertialAlphaOffset = 0;
  48336. _this.inertialBetaOffset = 0;
  48337. _this.inertialRadiusOffset = 0;
  48338. _this.inertialPanningX = 0;
  48339. _this.inertialPanningY = 0;
  48340. };
  48341. };
  48342. ArcRotateCamera.prototype.detachControl = function (element) {
  48343. this.inputs.detachElement(element);
  48344. if (this._reset) {
  48345. this._reset();
  48346. }
  48347. };
  48348. ArcRotateCamera.prototype._checkInputs = function () {
  48349. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48350. if (this._collisionTriggered) {
  48351. return;
  48352. }
  48353. this.inputs.checkInputs();
  48354. // Inertia
  48355. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48356. if (this.getScene().useRightHandedSystem) {
  48357. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48358. }
  48359. else {
  48360. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48361. }
  48362. this.beta += this.inertialBetaOffset;
  48363. this.radius -= this.inertialRadiusOffset;
  48364. this.inertialAlphaOffset *= this.inertia;
  48365. this.inertialBetaOffset *= this.inertia;
  48366. this.inertialRadiusOffset *= this.inertia;
  48367. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48368. this.inertialAlphaOffset = 0;
  48369. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48370. this.inertialBetaOffset = 0;
  48371. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48372. this.inertialRadiusOffset = 0;
  48373. }
  48374. // Panning inertia
  48375. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48376. if (!this._localDirection) {
  48377. this._localDirection = BABYLON.Vector3.Zero();
  48378. this._transformedDirection = BABYLON.Vector3.Zero();
  48379. }
  48380. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48381. this._localDirection.multiplyInPlace(this.panningAxis);
  48382. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48383. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48384. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48385. if (!this.panningAxis.y) {
  48386. this._transformedDirection.y = 0;
  48387. }
  48388. if (!this._targetHost) {
  48389. if (this.panningDistanceLimit) {
  48390. this._transformedDirection.addInPlace(this._target);
  48391. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48392. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48393. this._target.copyFrom(this._transformedDirection);
  48394. }
  48395. }
  48396. else {
  48397. this._target.addInPlace(this._transformedDirection);
  48398. }
  48399. }
  48400. this.inertialPanningX *= this.panningInertia;
  48401. this.inertialPanningY *= this.panningInertia;
  48402. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48403. this.inertialPanningX = 0;
  48404. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48405. this.inertialPanningY = 0;
  48406. }
  48407. // Limits
  48408. this._checkLimits();
  48409. _super.prototype._checkInputs.call(this);
  48410. };
  48411. ArcRotateCamera.prototype._checkLimits = function () {
  48412. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48413. if (this.allowUpsideDown && this.beta > Math.PI) {
  48414. this.beta = this.beta - (2 * Math.PI);
  48415. }
  48416. }
  48417. else {
  48418. if (this.beta < this.lowerBetaLimit) {
  48419. this.beta = this.lowerBetaLimit;
  48420. }
  48421. }
  48422. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48423. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48424. this.beta = this.beta + (2 * Math.PI);
  48425. }
  48426. }
  48427. else {
  48428. if (this.beta > this.upperBetaLimit) {
  48429. this.beta = this.upperBetaLimit;
  48430. }
  48431. }
  48432. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48433. this.alpha = this.lowerAlphaLimit;
  48434. }
  48435. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48436. this.alpha = this.upperAlphaLimit;
  48437. }
  48438. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48439. this.radius = this.lowerRadiusLimit;
  48440. }
  48441. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48442. this.radius = this.upperRadiusLimit;
  48443. }
  48444. };
  48445. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48446. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48447. this.radius = this._computationVector.length();
  48448. if (this.radius === 0) {
  48449. this.radius = 0.0001; // Just to avoid division by zero
  48450. }
  48451. // Alpha
  48452. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48453. if (this._computationVector.z < 0) {
  48454. this.alpha = 2 * Math.PI - this.alpha;
  48455. }
  48456. // Beta
  48457. this.beta = Math.acos(this._computationVector.y / this.radius);
  48458. this._checkLimits();
  48459. };
  48460. ArcRotateCamera.prototype.setPosition = function (position) {
  48461. if (this.position.equals(position)) {
  48462. return;
  48463. }
  48464. this.position.copyFrom(position);
  48465. this.rebuildAnglesAndRadius();
  48466. };
  48467. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48468. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48469. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48470. if (target.getBoundingInfo) {
  48471. if (toBoundingCenter) {
  48472. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48473. }
  48474. else {
  48475. this._targetBoundingCenter = null;
  48476. }
  48477. this._targetHost = target;
  48478. this._target = this._getTargetPosition();
  48479. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48480. }
  48481. else {
  48482. var newTarget = target;
  48483. var currentTarget = this._getTargetPosition();
  48484. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48485. return;
  48486. }
  48487. this._targetHost = null;
  48488. this._target = newTarget;
  48489. this._targetBoundingCenter = null;
  48490. this.onMeshTargetChangedObservable.notifyObservers(null);
  48491. }
  48492. this.rebuildAnglesAndRadius();
  48493. };
  48494. ArcRotateCamera.prototype._getViewMatrix = function () {
  48495. // Compute
  48496. var cosa = Math.cos(this.alpha);
  48497. var sina = Math.sin(this.alpha);
  48498. var cosb = Math.cos(this.beta);
  48499. var sinb = Math.sin(this.beta);
  48500. if (sinb === 0) {
  48501. sinb = 0.0001;
  48502. }
  48503. var target = this._getTargetPosition();
  48504. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48505. target.addToRef(this._computationVector, this._newPosition);
  48506. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48507. if (!this._collider) {
  48508. this._collider = new BABYLON.Collider();
  48509. }
  48510. this._collider._radius = this.collisionRadius;
  48511. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48512. this._collisionTriggered = true;
  48513. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48514. }
  48515. else {
  48516. this.position.copyFrom(this._newPosition);
  48517. var up = this.upVector;
  48518. if (this.allowUpsideDown && sinb < 0) {
  48519. up = up.clone();
  48520. up = up.negate();
  48521. }
  48522. if (this.getScene().useRightHandedSystem) {
  48523. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48524. }
  48525. else {
  48526. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48527. }
  48528. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48529. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48530. }
  48531. this._currentTarget = target;
  48532. return this._viewMatrix;
  48533. };
  48534. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48536. meshes = meshes || this.getScene().meshes;
  48537. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48538. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48539. this.radius = distance * this.zoomOnFactor;
  48540. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48541. };
  48542. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48543. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48544. var meshesOrMinMaxVector;
  48545. var distance;
  48546. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48547. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48548. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48549. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48550. }
  48551. else { //minMaxVector and distance
  48552. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48553. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48554. distance = minMaxVectorAndDistance.distance;
  48555. }
  48556. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48557. if (!doNotUpdateMaxZ) {
  48558. this.maxZ = distance * 2;
  48559. }
  48560. };
  48561. /**
  48562. * @override
  48563. * Override Camera.createRigCamera
  48564. */
  48565. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48566. var alphaShift = 0;
  48567. switch (this.cameraRigMode) {
  48568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48571. case BABYLON.Camera.RIG_MODE_VR:
  48572. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48573. break;
  48574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48575. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48576. break;
  48577. }
  48578. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48579. rigCam._cameraRigParams = {};
  48580. return rigCam;
  48581. };
  48582. /**
  48583. * @override
  48584. * Override Camera._updateRigCameras
  48585. */
  48586. ArcRotateCamera.prototype._updateRigCameras = function () {
  48587. var camLeft = this._rigCameras[0];
  48588. var camRight = this._rigCameras[1];
  48589. camLeft.beta = camRight.beta = this.beta;
  48590. camLeft.radius = camRight.radius = this.radius;
  48591. switch (this.cameraRigMode) {
  48592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48595. case BABYLON.Camera.RIG_MODE_VR:
  48596. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48597. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48598. break;
  48599. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48600. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48601. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48602. break;
  48603. }
  48604. _super.prototype._updateRigCameras.call(this);
  48605. };
  48606. ArcRotateCamera.prototype.dispose = function () {
  48607. this.inputs.clear();
  48608. _super.prototype.dispose.call(this);
  48609. };
  48610. ArcRotateCamera.prototype.getClassName = function () {
  48611. return "ArcRotateCamera";
  48612. };
  48613. __decorate([
  48614. BABYLON.serialize()
  48615. ], ArcRotateCamera.prototype, "alpha", void 0);
  48616. __decorate([
  48617. BABYLON.serialize()
  48618. ], ArcRotateCamera.prototype, "beta", void 0);
  48619. __decorate([
  48620. BABYLON.serialize()
  48621. ], ArcRotateCamera.prototype, "radius", void 0);
  48622. __decorate([
  48623. BABYLON.serializeAsVector3("target")
  48624. ], ArcRotateCamera.prototype, "_target", void 0);
  48625. __decorate([
  48626. BABYLON.serialize()
  48627. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48628. __decorate([
  48629. BABYLON.serialize()
  48630. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48631. __decorate([
  48632. BABYLON.serialize()
  48633. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48634. __decorate([
  48635. BABYLON.serialize()
  48636. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48637. __decorate([
  48638. BABYLON.serialize()
  48639. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48640. __decorate([
  48641. BABYLON.serialize()
  48642. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48643. __decorate([
  48644. BABYLON.serialize()
  48645. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48646. __decorate([
  48647. BABYLON.serialize()
  48648. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48649. __decorate([
  48650. BABYLON.serialize()
  48651. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48652. __decorate([
  48653. BABYLON.serialize()
  48654. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48655. __decorate([
  48656. BABYLON.serialize()
  48657. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48658. __decorate([
  48659. BABYLON.serialize()
  48660. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48661. __decorate([
  48662. BABYLON.serialize()
  48663. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48664. __decorate([
  48665. BABYLON.serializeAsVector3()
  48666. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48667. __decorate([
  48668. BABYLON.serialize()
  48669. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48670. __decorate([
  48671. BABYLON.serialize()
  48672. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48673. __decorate([
  48674. BABYLON.serialize()
  48675. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48676. return ArcRotateCamera;
  48677. }(BABYLON.TargetCamera));
  48678. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48679. })(BABYLON || (BABYLON = {}));
  48680. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48681. var BABYLON;
  48682. (function (BABYLON) {
  48683. /**
  48684. * The HemisphericLight simulates the ambient environment light,
  48685. * so the passed direction is the light reflection direction, not the incoming direction.
  48686. */
  48687. var HemisphericLight = /** @class */ (function (_super) {
  48688. __extends(HemisphericLight, _super);
  48689. /**
  48690. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48691. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48692. * The HemisphericLight can't cast shadows.
  48693. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48694. * @param name The friendly name of the light
  48695. * @param direction The direction of the light reflection
  48696. * @param scene The scene the light belongs to
  48697. */
  48698. function HemisphericLight(name, direction, scene) {
  48699. var _this = _super.call(this, name, scene) || this;
  48700. /**
  48701. * The groundColor is the light in the opposite direction to the one specified during creation.
  48702. * 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.
  48703. */
  48704. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48705. _this.direction = direction || BABYLON.Vector3.Up();
  48706. return _this;
  48707. }
  48708. HemisphericLight.prototype._buildUniformLayout = function () {
  48709. this._uniformBuffer.addUniform("vLightData", 4);
  48710. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48711. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48712. this._uniformBuffer.addUniform("vLightGround", 3);
  48713. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48714. this._uniformBuffer.addUniform("depthValues", 2);
  48715. this._uniformBuffer.create();
  48716. };
  48717. /**
  48718. * Returns the string "HemisphericLight".
  48719. * @return The class name
  48720. */
  48721. HemisphericLight.prototype.getClassName = function () {
  48722. return "HemisphericLight";
  48723. };
  48724. /**
  48725. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48726. * Returns the updated direction.
  48727. * @param target The target the direction should point to
  48728. * @return The computed direction
  48729. */
  48730. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48731. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48732. return this.direction;
  48733. };
  48734. /**
  48735. * Returns the shadow generator associated to the light.
  48736. * @returns Always null for hemispheric lights because it does not support shadows.
  48737. */
  48738. HemisphericLight.prototype.getShadowGenerator = function () {
  48739. return null;
  48740. };
  48741. /**
  48742. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48743. * @param effect The effect to update
  48744. * @param lightIndex The index of the light in the effect to update
  48745. * @returns The hemispheric light
  48746. */
  48747. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48748. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48749. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48750. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48751. return this;
  48752. };
  48753. /**
  48754. * @ignore internal use only.
  48755. */
  48756. HemisphericLight.prototype._getWorldMatrix = function () {
  48757. if (!this._worldMatrix) {
  48758. this._worldMatrix = BABYLON.Matrix.Identity();
  48759. }
  48760. return this._worldMatrix;
  48761. };
  48762. /**
  48763. * Returns the integer 3.
  48764. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48765. */
  48766. HemisphericLight.prototype.getTypeID = function () {
  48767. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48768. };
  48769. __decorate([
  48770. BABYLON.serializeAsColor3()
  48771. ], HemisphericLight.prototype, "groundColor", void 0);
  48772. __decorate([
  48773. BABYLON.serializeAsVector3()
  48774. ], HemisphericLight.prototype, "direction", void 0);
  48775. return HemisphericLight;
  48776. }(BABYLON.Light));
  48777. BABYLON.HemisphericLight = HemisphericLight;
  48778. })(BABYLON || (BABYLON = {}));
  48779. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48780. var BABYLON;
  48781. (function (BABYLON) {
  48782. /**
  48783. * Base implementation IShadowLight
  48784. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48785. */
  48786. var ShadowLight = /** @class */ (function (_super) {
  48787. __extends(ShadowLight, _super);
  48788. function ShadowLight() {
  48789. var _this = _super !== null && _super.apply(this, arguments) || this;
  48790. _this._needProjectionMatrixCompute = true;
  48791. return _this;
  48792. }
  48793. ShadowLight.prototype._setPosition = function (value) {
  48794. this._position = value;
  48795. };
  48796. Object.defineProperty(ShadowLight.prototype, "position", {
  48797. /**
  48798. * Sets the position the shadow will be casted from. Also use as the light position for both
  48799. * point and spot lights.
  48800. */
  48801. get: function () {
  48802. return this._position;
  48803. },
  48804. /**
  48805. * Sets the position the shadow will be casted from. Also use as the light position for both
  48806. * point and spot lights.
  48807. */
  48808. set: function (value) {
  48809. this._setPosition(value);
  48810. },
  48811. enumerable: true,
  48812. configurable: true
  48813. });
  48814. ShadowLight.prototype._setDirection = function (value) {
  48815. this._direction = value;
  48816. };
  48817. Object.defineProperty(ShadowLight.prototype, "direction", {
  48818. /**
  48819. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48820. * Also use as the light direction on spot and directional lights.
  48821. */
  48822. get: function () {
  48823. return this._direction;
  48824. },
  48825. /**
  48826. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48827. * Also use as the light direction on spot and directional lights.
  48828. */
  48829. set: function (value) {
  48830. this._setDirection(value);
  48831. },
  48832. enumerable: true,
  48833. configurable: true
  48834. });
  48835. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48836. /**
  48837. * Gets the shadow projection clipping minimum z value.
  48838. */
  48839. get: function () {
  48840. return this._shadowMinZ;
  48841. },
  48842. /**
  48843. * Sets the shadow projection clipping minimum z value.
  48844. */
  48845. set: function (value) {
  48846. this._shadowMinZ = value;
  48847. this.forceProjectionMatrixCompute();
  48848. },
  48849. enumerable: true,
  48850. configurable: true
  48851. });
  48852. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48853. /**
  48854. * Sets the shadow projection clipping maximum z value.
  48855. */
  48856. get: function () {
  48857. return this._shadowMaxZ;
  48858. },
  48859. /**
  48860. * Gets the shadow projection clipping maximum z value.
  48861. */
  48862. set: function (value) {
  48863. this._shadowMaxZ = value;
  48864. this.forceProjectionMatrixCompute();
  48865. },
  48866. enumerable: true,
  48867. configurable: true
  48868. });
  48869. /**
  48870. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48871. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48872. */
  48873. ShadowLight.prototype.computeTransformedInformation = function () {
  48874. if (this.parent && this.parent.getWorldMatrix) {
  48875. if (!this.transformedPosition) {
  48876. this.transformedPosition = BABYLON.Vector3.Zero();
  48877. }
  48878. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48879. // In case the direction is present.
  48880. if (this.direction) {
  48881. if (!this.transformedDirection) {
  48882. this.transformedDirection = BABYLON.Vector3.Zero();
  48883. }
  48884. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48885. }
  48886. return true;
  48887. }
  48888. return false;
  48889. };
  48890. /**
  48891. * Return the depth scale used for the shadow map.
  48892. * @returns the depth scale.
  48893. */
  48894. ShadowLight.prototype.getDepthScale = function () {
  48895. return 50.0;
  48896. };
  48897. /**
  48898. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48899. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48900. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48901. */
  48902. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48903. return this.transformedDirection ? this.transformedDirection : this.direction;
  48904. };
  48905. /**
  48906. * Returns the ShadowLight absolute position in the World.
  48907. * @returns the position vector in world space
  48908. */
  48909. ShadowLight.prototype.getAbsolutePosition = function () {
  48910. return this.transformedPosition ? this.transformedPosition : this.position;
  48911. };
  48912. /**
  48913. * Sets the ShadowLight direction toward the passed target.
  48914. * @param target The point tot target in local space
  48915. * @returns the updated ShadowLight direction
  48916. */
  48917. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48918. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48919. return this.direction;
  48920. };
  48921. /**
  48922. * Returns the light rotation in euler definition.
  48923. * @returns the x y z rotation in local space.
  48924. */
  48925. ShadowLight.prototype.getRotation = function () {
  48926. this.direction.normalize();
  48927. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48928. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48929. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48930. };
  48931. /**
  48932. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48933. * @returns true if a cube texture needs to be use
  48934. */
  48935. ShadowLight.prototype.needCube = function () {
  48936. return false;
  48937. };
  48938. /**
  48939. * Detects if the projection matrix requires to be recomputed this frame.
  48940. * @returns true if it requires to be recomputed otherwise, false.
  48941. */
  48942. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48943. return this._needProjectionMatrixCompute;
  48944. };
  48945. /**
  48946. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48947. */
  48948. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48949. this._needProjectionMatrixCompute = true;
  48950. };
  48951. /**
  48952. * Get the world matrix of the sahdow lights.
  48953. * @ignore Internal Use Only
  48954. */
  48955. ShadowLight.prototype._getWorldMatrix = function () {
  48956. if (!this._worldMatrix) {
  48957. this._worldMatrix = BABYLON.Matrix.Identity();
  48958. }
  48959. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48960. return this._worldMatrix;
  48961. };
  48962. /**
  48963. * Gets the minZ used for shadow according to both the scene and the light.
  48964. * @param activeCamera The camera we are returning the min for
  48965. * @returns the depth min z
  48966. */
  48967. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48968. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48969. };
  48970. /**
  48971. * Gets the maxZ used for shadow according to both the scene and the light.
  48972. * @param activeCamera The camera we are returning the max for
  48973. * @returns the depth max z
  48974. */
  48975. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48976. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48977. };
  48978. /**
  48979. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48980. * @param matrix The materix to updated with the projection information
  48981. * @param viewMatrix The transform matrix of the light
  48982. * @param renderList The list of mesh to render in the map
  48983. * @returns The current light
  48984. */
  48985. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48986. if (this.customProjectionMatrixBuilder) {
  48987. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48988. }
  48989. else {
  48990. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48991. }
  48992. return this;
  48993. };
  48994. __decorate([
  48995. BABYLON.serializeAsVector3()
  48996. ], ShadowLight.prototype, "position", null);
  48997. __decorate([
  48998. BABYLON.serializeAsVector3()
  48999. ], ShadowLight.prototype, "direction", null);
  49000. __decorate([
  49001. BABYLON.serialize()
  49002. ], ShadowLight.prototype, "shadowMinZ", null);
  49003. __decorate([
  49004. BABYLON.serialize()
  49005. ], ShadowLight.prototype, "shadowMaxZ", null);
  49006. return ShadowLight;
  49007. }(BABYLON.Light));
  49008. BABYLON.ShadowLight = ShadowLight;
  49009. })(BABYLON || (BABYLON = {}));
  49010. //# sourceMappingURL=babylon.shadowLight.js.map
  49011. var BABYLON;
  49012. (function (BABYLON) {
  49013. /**
  49014. * A point light is a light defined by an unique point in world space.
  49015. * The light is emitted in every direction from this point.
  49016. * A good example of a point light is a standard light bulb.
  49017. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49018. */
  49019. var PointLight = /** @class */ (function (_super) {
  49020. __extends(PointLight, _super);
  49021. /**
  49022. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49023. * A PointLight emits the light in every direction.
  49024. * It can cast shadows.
  49025. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49026. * ```javascript
  49027. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49028. * ```
  49029. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49030. * @param name The light friendly name
  49031. * @param position The position of the point light in the scene
  49032. * @param scene The scene the lights belongs to
  49033. */
  49034. function PointLight(name, position, scene) {
  49035. var _this = _super.call(this, name, scene) || this;
  49036. _this._shadowAngle = Math.PI / 2;
  49037. _this.position = position;
  49038. return _this;
  49039. }
  49040. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49041. /**
  49042. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49043. * This specifies what angle the shadow will use to be created.
  49044. *
  49045. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49046. */
  49047. get: function () {
  49048. return this._shadowAngle;
  49049. },
  49050. /**
  49051. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49052. * This specifies what angle the shadow will use to be created.
  49053. *
  49054. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49055. */
  49056. set: function (value) {
  49057. this._shadowAngle = value;
  49058. this.forceProjectionMatrixCompute();
  49059. },
  49060. enumerable: true,
  49061. configurable: true
  49062. });
  49063. Object.defineProperty(PointLight.prototype, "direction", {
  49064. /**
  49065. * Gets the direction if it has been set.
  49066. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49067. */
  49068. get: function () {
  49069. return this._direction;
  49070. },
  49071. /**
  49072. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49073. */
  49074. set: function (value) {
  49075. var previousNeedCube = this.needCube();
  49076. this._direction = value;
  49077. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49078. this._shadowGenerator.recreateShadowMap();
  49079. }
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. /**
  49085. * Returns the string "PointLight"
  49086. * @returns the class name
  49087. */
  49088. PointLight.prototype.getClassName = function () {
  49089. return "PointLight";
  49090. };
  49091. /**
  49092. * Returns the integer 0.
  49093. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49094. */
  49095. PointLight.prototype.getTypeID = function () {
  49096. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49097. };
  49098. /**
  49099. * Specifies wether or not the shadowmap should be a cube texture.
  49100. * @returns true if the shadowmap needs to be a cube texture.
  49101. */
  49102. PointLight.prototype.needCube = function () {
  49103. return !this.direction;
  49104. };
  49105. /**
  49106. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49107. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49108. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49109. */
  49110. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49111. if (this.direction) {
  49112. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49113. }
  49114. else {
  49115. switch (faceIndex) {
  49116. case 0:
  49117. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49118. case 1:
  49119. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49120. case 2:
  49121. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49122. case 3:
  49123. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49124. case 4:
  49125. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49126. case 5:
  49127. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49128. }
  49129. }
  49130. return BABYLON.Vector3.Zero();
  49131. };
  49132. /**
  49133. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49134. * - fov = PI / 2
  49135. * - aspect ratio : 1.0
  49136. * - z-near and far equal to the active camera minZ and maxZ.
  49137. * Returns the PointLight.
  49138. */
  49139. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49140. var activeCamera = this.getScene().activeCamera;
  49141. if (!activeCamera) {
  49142. return;
  49143. }
  49144. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49145. };
  49146. PointLight.prototype._buildUniformLayout = function () {
  49147. this._uniformBuffer.addUniform("vLightData", 4);
  49148. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49149. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49150. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49151. this._uniformBuffer.addUniform("depthValues", 2);
  49152. this._uniformBuffer.create();
  49153. };
  49154. /**
  49155. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49156. * @param effect The effect to update
  49157. * @param lightIndex The index of the light in the effect to update
  49158. * @returns The point light
  49159. */
  49160. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49161. if (this.computeTransformedInformation()) {
  49162. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49163. return this;
  49164. }
  49165. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49166. return this;
  49167. };
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], PointLight.prototype, "shadowAngle", null);
  49171. return PointLight;
  49172. }(BABYLON.ShadowLight));
  49173. BABYLON.PointLight = PointLight;
  49174. })(BABYLON || (BABYLON = {}));
  49175. //# sourceMappingURL=babylon.pointLight.js.map
  49176. var BABYLON;
  49177. (function (BABYLON) {
  49178. /**
  49179. * A directional light is defined by a direction (what a surprise!).
  49180. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49181. * 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.
  49182. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49183. */
  49184. var DirectionalLight = /** @class */ (function (_super) {
  49185. __extends(DirectionalLight, _super);
  49186. /**
  49187. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49188. * The directional light is emitted from everywhere in the given direction.
  49189. * It can cast shawdows.
  49190. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49191. * @param name The friendly name of the light
  49192. * @param direction The direction of the light
  49193. * @param scene The scene the light belongs to
  49194. */
  49195. function DirectionalLight(name, direction, scene) {
  49196. var _this = _super.call(this, name, scene) || this;
  49197. _this._shadowFrustumSize = 0;
  49198. _this._shadowOrthoScale = 0.1;
  49199. /**
  49200. * Automatically compute the projection matrix to best fit (including all the casters)
  49201. * on each frame.
  49202. */
  49203. _this.autoUpdateExtends = true;
  49204. // Cache
  49205. _this._orthoLeft = Number.MAX_VALUE;
  49206. _this._orthoRight = Number.MIN_VALUE;
  49207. _this._orthoTop = Number.MIN_VALUE;
  49208. _this._orthoBottom = Number.MAX_VALUE;
  49209. _this.position = direction.scale(-1.0);
  49210. _this.direction = direction;
  49211. return _this;
  49212. }
  49213. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49214. /**
  49215. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49216. */
  49217. get: function () {
  49218. return this._shadowFrustumSize;
  49219. },
  49220. /**
  49221. * Specifies a fix frustum size for the shadow generation.
  49222. */
  49223. set: function (value) {
  49224. this._shadowFrustumSize = value;
  49225. this.forceProjectionMatrixCompute();
  49226. },
  49227. enumerable: true,
  49228. configurable: true
  49229. });
  49230. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49231. /**
  49232. * Gets the shadow projection scale against the optimal computed one.
  49233. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49234. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49235. */
  49236. get: function () {
  49237. return this._shadowOrthoScale;
  49238. },
  49239. /**
  49240. * Sets the shadow projection scale against the optimal computed one.
  49241. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49242. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49243. */
  49244. set: function (value) {
  49245. this._shadowOrthoScale = value;
  49246. this.forceProjectionMatrixCompute();
  49247. },
  49248. enumerable: true,
  49249. configurable: true
  49250. });
  49251. /**
  49252. * Returns the string "DirectionalLight".
  49253. * @return The class name
  49254. */
  49255. DirectionalLight.prototype.getClassName = function () {
  49256. return "DirectionalLight";
  49257. };
  49258. /**
  49259. * Returns the integer 1.
  49260. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49261. */
  49262. DirectionalLight.prototype.getTypeID = function () {
  49263. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49264. };
  49265. /**
  49266. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49267. * Returns the DirectionalLight Shadow projection matrix.
  49268. */
  49269. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49270. if (this.shadowFrustumSize > 0) {
  49271. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49272. }
  49273. else {
  49274. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49275. }
  49276. };
  49277. /**
  49278. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49279. * Returns the DirectionalLight Shadow projection matrix.
  49280. */
  49281. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49282. var activeCamera = this.getScene().activeCamera;
  49283. if (!activeCamera) {
  49284. return;
  49285. }
  49286. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49287. };
  49288. /**
  49289. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49290. * Returns the DirectionalLight Shadow projection matrix.
  49291. */
  49292. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49293. var activeCamera = this.getScene().activeCamera;
  49294. if (!activeCamera) {
  49295. return;
  49296. }
  49297. // Check extends
  49298. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49299. var tempVector3 = BABYLON.Vector3.Zero();
  49300. this._orthoLeft = Number.MAX_VALUE;
  49301. this._orthoRight = Number.MIN_VALUE;
  49302. this._orthoTop = Number.MIN_VALUE;
  49303. this._orthoBottom = Number.MAX_VALUE;
  49304. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49305. var mesh = renderList[meshIndex];
  49306. if (!mesh) {
  49307. continue;
  49308. }
  49309. var boundingInfo = mesh.getBoundingInfo();
  49310. var boundingBox = boundingInfo.boundingBox;
  49311. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49312. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49313. if (tempVector3.x < this._orthoLeft)
  49314. this._orthoLeft = tempVector3.x;
  49315. if (tempVector3.y < this._orthoBottom)
  49316. this._orthoBottom = tempVector3.y;
  49317. if (tempVector3.x > this._orthoRight)
  49318. this._orthoRight = tempVector3.x;
  49319. if (tempVector3.y > this._orthoTop)
  49320. this._orthoTop = tempVector3.y;
  49321. }
  49322. }
  49323. }
  49324. var xOffset = this._orthoRight - this._orthoLeft;
  49325. var yOffset = this._orthoTop - this._orthoBottom;
  49326. 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);
  49327. };
  49328. DirectionalLight.prototype._buildUniformLayout = function () {
  49329. this._uniformBuffer.addUniform("vLightData", 4);
  49330. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49331. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49332. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49333. this._uniformBuffer.addUniform("depthValues", 2);
  49334. this._uniformBuffer.create();
  49335. };
  49336. /**
  49337. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49338. * @param effect The effect to update
  49339. * @param lightIndex The index of the light in the effect to update
  49340. * @returns The directional light
  49341. */
  49342. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49343. if (this.computeTransformedInformation()) {
  49344. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49345. return this;
  49346. }
  49347. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49348. return this;
  49349. };
  49350. /**
  49351. * Gets the minZ used for shadow according to both the scene and the light.
  49352. *
  49353. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49354. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49355. * @param activeCamera The camera we are returning the min for
  49356. * @returns the depth min z
  49357. */
  49358. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49359. return 1;
  49360. };
  49361. /**
  49362. * Gets the maxZ used for shadow according to both the scene and the light.
  49363. *
  49364. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49365. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49366. * @param activeCamera The camera we are returning the max for
  49367. * @returns the depth max z
  49368. */
  49369. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49370. return 1;
  49371. };
  49372. __decorate([
  49373. BABYLON.serialize()
  49374. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49375. __decorate([
  49376. BABYLON.serialize()
  49377. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49378. __decorate([
  49379. BABYLON.serialize()
  49380. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49381. return DirectionalLight;
  49382. }(BABYLON.ShadowLight));
  49383. BABYLON.DirectionalLight = DirectionalLight;
  49384. })(BABYLON || (BABYLON = {}));
  49385. //# sourceMappingURL=babylon.directionalLight.js.map
  49386. var BABYLON;
  49387. (function (BABYLON) {
  49388. /**
  49389. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49390. * These values define a cone of light starting from the position, emitting toward the direction.
  49391. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49392. * and the exponent defines the speed of the decay of the light with distance (reach).
  49393. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49394. */
  49395. var SpotLight = /** @class */ (function (_super) {
  49396. __extends(SpotLight, _super);
  49397. /**
  49398. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49399. * It can cast shadows.
  49400. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49401. * @param name The light friendly name
  49402. * @param position The position of the spot light in the scene
  49403. * @param direction The direction of the light in the scene
  49404. * @param angle The cone angle of the light in Radians
  49405. * @param exponent The light decay speed with the distance from the emission spot
  49406. * @param scene The scene the lights belongs to
  49407. */
  49408. function SpotLight(name, position, direction, angle, exponent, scene) {
  49409. var _this = _super.call(this, name, scene) || this;
  49410. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49411. _this._projectionTextureLightNear = 1e-6;
  49412. _this._projectionTextureLightFar = 1000.0;
  49413. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49414. _this._projectionTextureViewLightDirty = true;
  49415. _this._projectionTextureProjectionLightDirty = true;
  49416. _this._projectionTextureDirty = true;
  49417. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49418. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49419. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49420. _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);
  49421. _this.position = position;
  49422. _this.direction = direction;
  49423. _this.angle = angle;
  49424. _this.exponent = exponent;
  49425. return _this;
  49426. }
  49427. Object.defineProperty(SpotLight.prototype, "angle", {
  49428. /**
  49429. * Gets the cone angle of the spot light in Radians.
  49430. */
  49431. get: function () {
  49432. return this._angle;
  49433. },
  49434. /**
  49435. * Sets the cone angle of the spot light in Radians.
  49436. */
  49437. set: function (value) {
  49438. this._angle = value;
  49439. this._projectionTextureProjectionLightDirty = true;
  49440. this.forceProjectionMatrixCompute();
  49441. },
  49442. enumerable: true,
  49443. configurable: true
  49444. });
  49445. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49446. /**
  49447. * Allows scaling the angle of the light for shadow generation only.
  49448. */
  49449. get: function () {
  49450. return this._shadowAngleScale;
  49451. },
  49452. /**
  49453. * Allows scaling the angle of the light for shadow generation only.
  49454. */
  49455. set: function (value) {
  49456. this._shadowAngleScale = value;
  49457. this.forceProjectionMatrixCompute();
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49463. /**
  49464. * Allows reading the projecton texture
  49465. */
  49466. get: function () {
  49467. return this._projectionTextureMatrix;
  49468. },
  49469. enumerable: true,
  49470. configurable: true
  49471. });
  49472. ;
  49473. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49474. /**
  49475. * Gets the near clip of the Spotlight for texture projection.
  49476. */
  49477. get: function () {
  49478. return this._projectionTextureLightNear;
  49479. },
  49480. /**
  49481. * Sets the near clip of the Spotlight for texture projection.
  49482. */
  49483. set: function (value) {
  49484. this._projectionTextureLightNear = value;
  49485. this._projectionTextureProjectionLightDirty = true;
  49486. },
  49487. enumerable: true,
  49488. configurable: true
  49489. });
  49490. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49491. /**
  49492. * Gets the far clip of the Spotlight for texture projection.
  49493. */
  49494. get: function () {
  49495. return this._projectionTextureLightFar;
  49496. },
  49497. /**
  49498. * Sets the far clip of the Spotlight for texture projection.
  49499. */
  49500. set: function (value) {
  49501. this._projectionTextureLightFar = value;
  49502. this._projectionTextureProjectionLightDirty = true;
  49503. },
  49504. enumerable: true,
  49505. configurable: true
  49506. });
  49507. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49508. /**
  49509. * Gets the Up vector of the Spotlight for texture projection.
  49510. */
  49511. get: function () {
  49512. return this._projectionTextureUpDirection;
  49513. },
  49514. /**
  49515. * Sets the Up vector of the Spotlight for texture projection.
  49516. */
  49517. set: function (value) {
  49518. this._projectionTextureUpDirection = value;
  49519. this._projectionTextureProjectionLightDirty = true;
  49520. },
  49521. enumerable: true,
  49522. configurable: true
  49523. });
  49524. ;
  49525. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49526. /**
  49527. * Gets the projection texture of the light.
  49528. */
  49529. get: function () {
  49530. return this._projectionTexture;
  49531. },
  49532. /**
  49533. * Sets the projection texture of the light.
  49534. */
  49535. set: function (value) {
  49536. this._projectionTexture = value;
  49537. this._projectionTextureDirty = true;
  49538. },
  49539. enumerable: true,
  49540. configurable: true
  49541. });
  49542. /**
  49543. * Returns the string "SpotLight".
  49544. * @returns the class name
  49545. */
  49546. SpotLight.prototype.getClassName = function () {
  49547. return "SpotLight";
  49548. };
  49549. /**
  49550. * Returns the integer 2.
  49551. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49552. */
  49553. SpotLight.prototype.getTypeID = function () {
  49554. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49555. };
  49556. /**
  49557. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49558. */
  49559. SpotLight.prototype._setDirection = function (value) {
  49560. _super.prototype._setDirection.call(this, value);
  49561. this._projectionTextureViewLightDirty = true;
  49562. };
  49563. /**
  49564. * Overrides the position setter to recompute the projection texture view light Matrix.
  49565. */
  49566. SpotLight.prototype._setPosition = function (value) {
  49567. _super.prototype._setPosition.call(this, value);
  49568. this._projectionTextureViewLightDirty = true;
  49569. };
  49570. /**
  49571. * 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.
  49572. * Returns the SpotLight.
  49573. */
  49574. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49575. var activeCamera = this.getScene().activeCamera;
  49576. if (!activeCamera) {
  49577. return;
  49578. }
  49579. this._shadowAngleScale = this._shadowAngleScale || 1;
  49580. var angle = this._shadowAngleScale * this._angle;
  49581. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49582. };
  49583. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49584. this._projectionTextureViewLightDirty = false;
  49585. this._projectionTextureDirty = true;
  49586. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49587. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49588. };
  49589. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49590. this._projectionTextureProjectionLightDirty = false;
  49591. this._projectionTextureDirty = true;
  49592. var light_far = this.projectionTextureLightFar;
  49593. var light_near = this.projectionTextureLightNear;
  49594. var P = light_far / (light_far - light_near);
  49595. var Q = -P * light_near;
  49596. var S = 1.0 / Math.tan(this._angle / 2.0);
  49597. var A = 1.0;
  49598. 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);
  49599. };
  49600. /**
  49601. * Main function for light texture projection matrix computing.
  49602. */
  49603. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49604. this._projectionTextureDirty = false;
  49605. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49606. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49607. };
  49608. SpotLight.prototype._buildUniformLayout = function () {
  49609. this._uniformBuffer.addUniform("vLightData", 4);
  49610. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49611. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49612. this._uniformBuffer.addUniform("vLightDirection", 3);
  49613. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49614. this._uniformBuffer.addUniform("depthValues", 2);
  49615. this._uniformBuffer.create();
  49616. };
  49617. /**
  49618. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49619. * @param effect The effect to update
  49620. * @param lightIndex The index of the light in the effect to update
  49621. * @returns The spot light
  49622. */
  49623. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49624. var normalizeDirection;
  49625. if (this.computeTransformedInformation()) {
  49626. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49627. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49628. }
  49629. else {
  49630. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49631. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49632. }
  49633. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49634. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49635. if (this._projectionTextureViewLightDirty) {
  49636. this._computeProjectionTextureViewLightMatrix();
  49637. }
  49638. if (this._projectionTextureProjectionLightDirty) {
  49639. this._computeProjectionTextureProjectionLightMatrix();
  49640. }
  49641. if (this._projectionTextureDirty) {
  49642. this._computeProjectionTextureMatrix();
  49643. }
  49644. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49645. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49646. }
  49647. return this;
  49648. };
  49649. /**
  49650. * Disposes the light and the associated resources.
  49651. */
  49652. SpotLight.prototype.dispose = function () {
  49653. _super.prototype.dispose.call(this);
  49654. if (this._projectionTexture) {
  49655. this._projectionTexture.dispose();
  49656. }
  49657. };
  49658. __decorate([
  49659. BABYLON.serialize()
  49660. ], SpotLight.prototype, "angle", null);
  49661. __decorate([
  49662. BABYLON.serialize()
  49663. ], SpotLight.prototype, "shadowAngleScale", null);
  49664. __decorate([
  49665. BABYLON.serialize()
  49666. ], SpotLight.prototype, "exponent", void 0);
  49667. __decorate([
  49668. BABYLON.serialize()
  49669. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49670. __decorate([
  49671. BABYLON.serialize()
  49672. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49673. __decorate([
  49674. BABYLON.serialize()
  49675. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49676. __decorate([
  49677. BABYLON.serializeAsTexture("projectedLightTexture")
  49678. ], SpotLight.prototype, "_projectionTexture", void 0);
  49679. return SpotLight;
  49680. }(BABYLON.ShadowLight));
  49681. BABYLON.SpotLight = SpotLight;
  49682. })(BABYLON || (BABYLON = {}));
  49683. //# sourceMappingURL=babylon.spotLight.js.map
  49684. var BABYLON;
  49685. (function (BABYLON) {
  49686. /**
  49687. * Class used to override all child animations of a given target
  49688. */
  49689. var AnimationPropertiesOverride = /** @class */ (function () {
  49690. function AnimationPropertiesOverride() {
  49691. /**
  49692. * Gets or sets a value indicating if animation blending must be used
  49693. */
  49694. this.enableBlending = false;
  49695. /**
  49696. * Gets or sets the blending speed to use when enableBlending is true
  49697. */
  49698. this.blendingSpeed = 0.01;
  49699. /**
  49700. * Gets or sets the default loop mode to use
  49701. */
  49702. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49703. }
  49704. return AnimationPropertiesOverride;
  49705. }());
  49706. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49707. })(BABYLON || (BABYLON = {}));
  49708. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49709. var BABYLON;
  49710. (function (BABYLON) {
  49711. var AnimationRange = /** @class */ (function () {
  49712. function AnimationRange(name, from, to) {
  49713. this.name = name;
  49714. this.from = from;
  49715. this.to = to;
  49716. }
  49717. AnimationRange.prototype.clone = function () {
  49718. return new AnimationRange(this.name, this.from, this.to);
  49719. };
  49720. return AnimationRange;
  49721. }());
  49722. BABYLON.AnimationRange = AnimationRange;
  49723. /**
  49724. * Composed of a frame, and an action function
  49725. */
  49726. var AnimationEvent = /** @class */ (function () {
  49727. function AnimationEvent(frame, action, onlyOnce) {
  49728. this.frame = frame;
  49729. this.action = action;
  49730. this.onlyOnce = onlyOnce;
  49731. this.isDone = false;
  49732. }
  49733. return AnimationEvent;
  49734. }());
  49735. BABYLON.AnimationEvent = AnimationEvent;
  49736. var PathCursor = /** @class */ (function () {
  49737. function PathCursor(path) {
  49738. this.path = path;
  49739. this._onchange = new Array();
  49740. this.value = 0;
  49741. this.animations = new Array();
  49742. }
  49743. PathCursor.prototype.getPoint = function () {
  49744. var point = this.path.getPointAtLengthPosition(this.value);
  49745. return new BABYLON.Vector3(point.x, 0, point.y);
  49746. };
  49747. PathCursor.prototype.moveAhead = function (step) {
  49748. if (step === void 0) { step = 0.002; }
  49749. this.move(step);
  49750. return this;
  49751. };
  49752. PathCursor.prototype.moveBack = function (step) {
  49753. if (step === void 0) { step = 0.002; }
  49754. this.move(-step);
  49755. return this;
  49756. };
  49757. PathCursor.prototype.move = function (step) {
  49758. if (Math.abs(step) > 1) {
  49759. throw "step size should be less than 1.";
  49760. }
  49761. this.value += step;
  49762. this.ensureLimits();
  49763. this.raiseOnChange();
  49764. return this;
  49765. };
  49766. PathCursor.prototype.ensureLimits = function () {
  49767. while (this.value > 1) {
  49768. this.value -= 1;
  49769. }
  49770. while (this.value < 0) {
  49771. this.value += 1;
  49772. }
  49773. return this;
  49774. };
  49775. // used by animation engine
  49776. PathCursor.prototype.raiseOnChange = function () {
  49777. var _this = this;
  49778. this._onchange.forEach(function (f) { return f(_this); });
  49779. return this;
  49780. };
  49781. PathCursor.prototype.onchange = function (f) {
  49782. this._onchange.push(f);
  49783. return this;
  49784. };
  49785. return PathCursor;
  49786. }());
  49787. BABYLON.PathCursor = PathCursor;
  49788. var AnimationKeyInterpolation;
  49789. (function (AnimationKeyInterpolation) {
  49790. /**
  49791. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49792. */
  49793. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49794. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49795. /**
  49796. * Class used to store any kind of animation
  49797. */
  49798. var Animation = /** @class */ (function () {
  49799. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49800. this.name = name;
  49801. this.targetProperty = targetProperty;
  49802. this.framePerSecond = framePerSecond;
  49803. this.dataType = dataType;
  49804. this.loopMode = loopMode;
  49805. this.enableBlending = enableBlending;
  49806. this._runtimeAnimations = new Array();
  49807. // The set of event that will be linked to this animation
  49808. this._events = new Array();
  49809. this.blendingSpeed = 0.01;
  49810. this._ranges = {};
  49811. this.targetPropertyPath = targetProperty.split(".");
  49812. this.dataType = dataType;
  49813. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49814. }
  49815. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49816. var dataType = undefined;
  49817. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49818. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49819. }
  49820. else if (from instanceof BABYLON.Quaternion) {
  49821. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49822. }
  49823. else if (from instanceof BABYLON.Vector3) {
  49824. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49825. }
  49826. else if (from instanceof BABYLON.Vector2) {
  49827. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49828. }
  49829. else if (from instanceof BABYLON.Color3) {
  49830. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49831. }
  49832. else if (from instanceof BABYLON.Size) {
  49833. dataType = Animation.ANIMATIONTYPE_SIZE;
  49834. }
  49835. if (dataType == undefined) {
  49836. return null;
  49837. }
  49838. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49839. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49840. animation.setKeys(keys);
  49841. if (easingFunction !== undefined) {
  49842. animation.setEasingFunction(easingFunction);
  49843. }
  49844. return animation;
  49845. };
  49846. /**
  49847. * Sets up an animation.
  49848. * @param property the property to animate
  49849. * @param animationType the animation type to apply
  49850. * @param easingFunction the easing function used in the animation
  49851. * @returns The created animation
  49852. */
  49853. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49854. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49855. animation.setEasingFunction(easingFunction);
  49856. return animation;
  49857. };
  49858. /**
  49859. * Create and start an animation on a node
  49860. * @param {string} name defines the name of the global animation that will be run on all nodes
  49861. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49862. * @param {string} targetProperty defines property to animate
  49863. * @param {number} framePerSecond defines the number of frame per second yo use
  49864. * @param {number} totalFrame defines the number of frames in total
  49865. * @param {any} from defines the initial value
  49866. * @param {any} to defines the final value
  49867. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49868. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49869. * @param onAnimationEnd defines the callback to call when animation end
  49870. * @returns the animatable created for this animation
  49871. */
  49872. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49873. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49874. if (!animation) {
  49875. return null;
  49876. }
  49877. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49878. };
  49879. /**
  49880. * Create and start an animation on a node and its descendants
  49881. * @param {string} name defines the name of the global animation that will be run on all nodes
  49882. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49883. * @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.
  49884. * @param {string} targetProperty defines property to animate
  49885. * @param {number} framePerSecond defines the number of frame per second yo use
  49886. * @param {number} totalFrame defines the number of frames in total
  49887. * @param {any} from defines the initial value
  49888. * @param {any} to defines the final value
  49889. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49890. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49891. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49892. * @returns the list of animatables created for all nodes
  49893. * @example https://www.babylonjs-playground.com/#MH0VLI
  49894. */
  49895. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49896. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49897. if (!animation) {
  49898. return null;
  49899. }
  49900. var scene = node.getScene();
  49901. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49902. };
  49903. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49904. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49905. if (!animation) {
  49906. return null;
  49907. }
  49908. node.animations.push(animation);
  49909. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49910. };
  49911. /**
  49912. * Transition property of the Camera to the target Value.
  49913. * @param property The property to transition
  49914. * @param targetValue The target Value of the property
  49915. * @param host The object where the property to animate belongs
  49916. * @param scene Scene used to run the animation
  49917. * @param frameRate Framerate (in frame/s) to use
  49918. * @param transition The transition type we want to use
  49919. * @param duration The duration of the animation, in milliseconds
  49920. * @param onAnimationEnd Call back trigger at the end of the animation.
  49921. */
  49922. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49923. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49924. if (duration <= 0) {
  49925. host[property] = targetValue;
  49926. if (onAnimationEnd) {
  49927. onAnimationEnd();
  49928. }
  49929. return null;
  49930. }
  49931. var endFrame = frameRate * (duration / 1000);
  49932. transition.setKeys([{
  49933. frame: 0,
  49934. value: host[property].clone ? host[property].clone() : host[property]
  49935. },
  49936. {
  49937. frame: endFrame,
  49938. value: targetValue
  49939. }]);
  49940. if (!host.animations) {
  49941. host.animations = [];
  49942. }
  49943. host.animations.push(transition);
  49944. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49945. animation.onAnimationEnd = onAnimationEnd;
  49946. return animation;
  49947. };
  49948. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49949. /**
  49950. * Return the array of runtime animations currently using this animation
  49951. */
  49952. get: function () {
  49953. return this._runtimeAnimations;
  49954. },
  49955. enumerable: true,
  49956. configurable: true
  49957. });
  49958. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49959. get: function () {
  49960. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49961. var runtimeAnimation = _a[_i];
  49962. if (!runtimeAnimation.isStopped) {
  49963. return true;
  49964. }
  49965. }
  49966. return false;
  49967. },
  49968. enumerable: true,
  49969. configurable: true
  49970. });
  49971. // Methods
  49972. /**
  49973. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49974. */
  49975. Animation.prototype.toString = function (fullDetails) {
  49976. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49977. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49978. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49979. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49980. if (fullDetails) {
  49981. ret += ", Ranges: {";
  49982. var first = true;
  49983. for (var name in this._ranges) {
  49984. if (first) {
  49985. ret += ", ";
  49986. first = false;
  49987. }
  49988. ret += name;
  49989. }
  49990. ret += "}";
  49991. }
  49992. return ret;
  49993. };
  49994. /**
  49995. * Add an event to this animation.
  49996. */
  49997. Animation.prototype.addEvent = function (event) {
  49998. this._events.push(event);
  49999. };
  50000. /**
  50001. * Remove all events found at the given frame
  50002. * @param frame
  50003. */
  50004. Animation.prototype.removeEvents = function (frame) {
  50005. for (var index = 0; index < this._events.length; index++) {
  50006. if (this._events[index].frame === frame) {
  50007. this._events.splice(index, 1);
  50008. index--;
  50009. }
  50010. }
  50011. };
  50012. Animation.prototype.getEvents = function () {
  50013. return this._events;
  50014. };
  50015. Animation.prototype.createRange = function (name, from, to) {
  50016. // check name not already in use; could happen for bones after serialized
  50017. if (!this._ranges[name]) {
  50018. this._ranges[name] = new AnimationRange(name, from, to);
  50019. }
  50020. };
  50021. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50022. if (deleteFrames === void 0) { deleteFrames = true; }
  50023. var range = this._ranges[name];
  50024. if (!range) {
  50025. return;
  50026. }
  50027. if (deleteFrames) {
  50028. var from = range.from;
  50029. var to = range.to;
  50030. // this loop MUST go high to low for multiple splices to work
  50031. for (var key = this._keys.length - 1; key >= 0; key--) {
  50032. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50033. this._keys.splice(key, 1);
  50034. }
  50035. }
  50036. }
  50037. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50038. };
  50039. Animation.prototype.getRange = function (name) {
  50040. return this._ranges[name];
  50041. };
  50042. Animation.prototype.getKeys = function () {
  50043. return this._keys;
  50044. };
  50045. Animation.prototype.getHighestFrame = function () {
  50046. var ret = 0;
  50047. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50048. if (ret < this._keys[key].frame) {
  50049. ret = this._keys[key].frame;
  50050. }
  50051. }
  50052. return ret;
  50053. };
  50054. Animation.prototype.getEasingFunction = function () {
  50055. return this._easingFunction;
  50056. };
  50057. Animation.prototype.setEasingFunction = function (easingFunction) {
  50058. this._easingFunction = easingFunction;
  50059. };
  50060. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50061. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50062. };
  50063. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50064. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50065. };
  50066. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50067. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50068. };
  50069. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50070. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50071. };
  50072. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50073. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50074. };
  50075. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50076. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50077. };
  50078. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50079. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50080. };
  50081. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50082. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50083. };
  50084. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50085. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50086. };
  50087. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50088. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50089. };
  50090. /**
  50091. * Defines the function to use to interpolate matrices
  50092. * @param startValue defines the start matrix
  50093. * @param endValue defines the end matrix
  50094. * @param gradient defines the gradient between both matrices
  50095. * @param result defines an optional target matrix where to store the interpolation
  50096. * @returns the interpolated matrix
  50097. */
  50098. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50099. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50100. if (result) {
  50101. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50102. return result;
  50103. }
  50104. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50105. }
  50106. if (result) {
  50107. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50108. return result;
  50109. }
  50110. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50111. };
  50112. Animation.prototype.clone = function () {
  50113. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50114. clone.enableBlending = this.enableBlending;
  50115. clone.blendingSpeed = this.blendingSpeed;
  50116. if (this._keys) {
  50117. clone.setKeys(this._keys);
  50118. }
  50119. if (this._ranges) {
  50120. clone._ranges = {};
  50121. for (var name in this._ranges) {
  50122. var range = this._ranges[name];
  50123. if (!range) {
  50124. continue;
  50125. }
  50126. clone._ranges[name] = range.clone();
  50127. }
  50128. }
  50129. return clone;
  50130. };
  50131. Animation.prototype.setKeys = function (values) {
  50132. this._keys = values.slice(0);
  50133. };
  50134. Animation.prototype.serialize = function () {
  50135. var serializationObject = {};
  50136. serializationObject.name = this.name;
  50137. serializationObject.property = this.targetProperty;
  50138. serializationObject.framePerSecond = this.framePerSecond;
  50139. serializationObject.dataType = this.dataType;
  50140. serializationObject.loopBehavior = this.loopMode;
  50141. serializationObject.enableBlending = this.enableBlending;
  50142. serializationObject.blendingSpeed = this.blendingSpeed;
  50143. var dataType = this.dataType;
  50144. serializationObject.keys = [];
  50145. var keys = this.getKeys();
  50146. for (var index = 0; index < keys.length; index++) {
  50147. var animationKey = keys[index];
  50148. var key = {};
  50149. key.frame = animationKey.frame;
  50150. switch (dataType) {
  50151. case Animation.ANIMATIONTYPE_FLOAT:
  50152. key.values = [animationKey.value];
  50153. break;
  50154. case Animation.ANIMATIONTYPE_QUATERNION:
  50155. case Animation.ANIMATIONTYPE_MATRIX:
  50156. case Animation.ANIMATIONTYPE_VECTOR3:
  50157. case Animation.ANIMATIONTYPE_COLOR3:
  50158. key.values = animationKey.value.asArray();
  50159. break;
  50160. }
  50161. serializationObject.keys.push(key);
  50162. }
  50163. serializationObject.ranges = [];
  50164. for (var name in this._ranges) {
  50165. var source = this._ranges[name];
  50166. if (!source) {
  50167. continue;
  50168. }
  50169. var range = {};
  50170. range.name = name;
  50171. range.from = source.from;
  50172. range.to = source.to;
  50173. serializationObject.ranges.push(range);
  50174. }
  50175. return serializationObject;
  50176. };
  50177. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50178. get: function () {
  50179. return Animation._ANIMATIONTYPE_FLOAT;
  50180. },
  50181. enumerable: true,
  50182. configurable: true
  50183. });
  50184. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50185. get: function () {
  50186. return Animation._ANIMATIONTYPE_VECTOR3;
  50187. },
  50188. enumerable: true,
  50189. configurable: true
  50190. });
  50191. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50192. get: function () {
  50193. return Animation._ANIMATIONTYPE_VECTOR2;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50199. get: function () {
  50200. return Animation._ANIMATIONTYPE_SIZE;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50206. get: function () {
  50207. return Animation._ANIMATIONTYPE_QUATERNION;
  50208. },
  50209. enumerable: true,
  50210. configurable: true
  50211. });
  50212. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50213. get: function () {
  50214. return Animation._ANIMATIONTYPE_MATRIX;
  50215. },
  50216. enumerable: true,
  50217. configurable: true
  50218. });
  50219. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50220. get: function () {
  50221. return Animation._ANIMATIONTYPE_COLOR3;
  50222. },
  50223. enumerable: true,
  50224. configurable: true
  50225. });
  50226. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50227. get: function () {
  50228. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50229. },
  50230. enumerable: true,
  50231. configurable: true
  50232. });
  50233. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50234. get: function () {
  50235. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50236. },
  50237. enumerable: true,
  50238. configurable: true
  50239. });
  50240. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50241. get: function () {
  50242. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Animation.Parse = function (parsedAnimation) {
  50248. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50249. var dataType = parsedAnimation.dataType;
  50250. var keys = [];
  50251. var data;
  50252. var index;
  50253. if (parsedAnimation.enableBlending) {
  50254. animation.enableBlending = parsedAnimation.enableBlending;
  50255. }
  50256. if (parsedAnimation.blendingSpeed) {
  50257. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50258. }
  50259. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50260. var key = parsedAnimation.keys[index];
  50261. var inTangent;
  50262. var outTangent;
  50263. switch (dataType) {
  50264. case Animation.ANIMATIONTYPE_FLOAT:
  50265. data = key.values[0];
  50266. if (key.values.length >= 1) {
  50267. inTangent = key.values[1];
  50268. }
  50269. if (key.values.length >= 2) {
  50270. outTangent = key.values[2];
  50271. }
  50272. break;
  50273. case Animation.ANIMATIONTYPE_QUATERNION:
  50274. data = BABYLON.Quaternion.FromArray(key.values);
  50275. if (key.values.length >= 8) {
  50276. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50277. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50278. inTangent = _inTangent;
  50279. }
  50280. }
  50281. if (key.values.length >= 12) {
  50282. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50283. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50284. outTangent = _outTangent;
  50285. }
  50286. }
  50287. break;
  50288. case Animation.ANIMATIONTYPE_MATRIX:
  50289. data = BABYLON.Matrix.FromArray(key.values);
  50290. break;
  50291. case Animation.ANIMATIONTYPE_COLOR3:
  50292. data = BABYLON.Color3.FromArray(key.values);
  50293. break;
  50294. case Animation.ANIMATIONTYPE_VECTOR3:
  50295. default:
  50296. data = BABYLON.Vector3.FromArray(key.values);
  50297. break;
  50298. }
  50299. var keyData = {};
  50300. keyData.frame = key.frame;
  50301. keyData.value = data;
  50302. if (inTangent != undefined) {
  50303. keyData.inTangent = inTangent;
  50304. }
  50305. if (outTangent != undefined) {
  50306. keyData.outTangent = outTangent;
  50307. }
  50308. keys.push(keyData);
  50309. }
  50310. animation.setKeys(keys);
  50311. if (parsedAnimation.ranges) {
  50312. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50313. data = parsedAnimation.ranges[index];
  50314. animation.createRange(data.name, data.from, data.to);
  50315. }
  50316. }
  50317. return animation;
  50318. };
  50319. Animation.AppendSerializedAnimations = function (source, destination) {
  50320. if (source.animations) {
  50321. destination.animations = [];
  50322. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50323. var animation = source.animations[animationIndex];
  50324. destination.animations.push(animation.serialize());
  50325. }
  50326. }
  50327. };
  50328. /**
  50329. * Use matrix interpolation instead of using direct key value when animating matrices
  50330. */
  50331. Animation.AllowMatricesInterpolation = false;
  50332. /**
  50333. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50334. */
  50335. Animation.AllowMatrixDecomposeForInterpolation = true;
  50336. // Statics
  50337. Animation._ANIMATIONTYPE_FLOAT = 0;
  50338. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50339. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50340. Animation._ANIMATIONTYPE_MATRIX = 3;
  50341. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50342. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50343. Animation._ANIMATIONTYPE_SIZE = 6;
  50344. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50345. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50346. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50347. return Animation;
  50348. }());
  50349. BABYLON.Animation = Animation;
  50350. })(BABYLON || (BABYLON = {}));
  50351. //# sourceMappingURL=babylon.animation.js.map
  50352. var BABYLON;
  50353. (function (BABYLON) {
  50354. /**
  50355. * This class defines the direct association between an animation and a target
  50356. */
  50357. var TargetedAnimation = /** @class */ (function () {
  50358. function TargetedAnimation() {
  50359. }
  50360. return TargetedAnimation;
  50361. }());
  50362. BABYLON.TargetedAnimation = TargetedAnimation;
  50363. /**
  50364. * Use this class to create coordinated animations on multiple targets
  50365. */
  50366. var AnimationGroup = /** @class */ (function () {
  50367. function AnimationGroup(name, scene) {
  50368. if (scene === void 0) { scene = null; }
  50369. this.name = name;
  50370. this._targetedAnimations = new Array();
  50371. this._animatables = new Array();
  50372. this._from = Number.MAX_VALUE;
  50373. this._to = -Number.MAX_VALUE;
  50374. this._speedRatio = 1;
  50375. this.onAnimationEndObservable = new BABYLON.Observable();
  50376. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50377. this._scene.animationGroups.push(this);
  50378. }
  50379. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50380. /**
  50381. * Define if the animations are started
  50382. */
  50383. get: function () {
  50384. return this._isStarted;
  50385. },
  50386. enumerable: true,
  50387. configurable: true
  50388. });
  50389. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50390. /**
  50391. * Gets or sets the speed ratio to use for all animations
  50392. */
  50393. get: function () {
  50394. return this._speedRatio;
  50395. },
  50396. /**
  50397. * Gets or sets the speed ratio to use for all animations
  50398. */
  50399. set: function (value) {
  50400. if (this._speedRatio === value) {
  50401. return;
  50402. }
  50403. this._speedRatio = value;
  50404. for (var index = 0; index < this._animatables.length; index++) {
  50405. var animatable = this._animatables[index];
  50406. animatable.speedRatio = this._speedRatio;
  50407. }
  50408. },
  50409. enumerable: true,
  50410. configurable: true
  50411. });
  50412. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50413. /**
  50414. * Gets the targeted animations for this animation group
  50415. */
  50416. get: function () {
  50417. return this._targetedAnimations;
  50418. },
  50419. enumerable: true,
  50420. configurable: true
  50421. });
  50422. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50423. /**
  50424. * returning the list of animatables controlled by this animation group.
  50425. */
  50426. get: function () {
  50427. return this._animatables;
  50428. },
  50429. enumerable: true,
  50430. configurable: true
  50431. });
  50432. /**
  50433. * Add an animation (with its target) in the group
  50434. * @param animation defines the animation we want to add
  50435. * @param target defines the target of the animation
  50436. * @returns the {BABYLON.TargetedAnimation} object
  50437. */
  50438. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50439. var targetedAnimation = {
  50440. animation: animation,
  50441. target: target
  50442. };
  50443. var keys = animation.getKeys();
  50444. if (this._from > keys[0].frame) {
  50445. this._from = keys[0].frame;
  50446. }
  50447. if (this._to < keys[keys.length - 1].frame) {
  50448. this._to = keys[keys.length - 1].frame;
  50449. }
  50450. this._targetedAnimations.push(targetedAnimation);
  50451. return targetedAnimation;
  50452. };
  50453. /**
  50454. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50455. * It can add constant keys at begin or end
  50456. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50457. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50458. */
  50459. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50460. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50461. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50462. beginFrame = Math.max(beginFrame, this._from);
  50463. endFrame = Math.min(endFrame, this._to);
  50464. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50465. var targetedAnimation = this._targetedAnimations[index];
  50466. var keys = targetedAnimation.animation.getKeys();
  50467. var startKey = keys[0];
  50468. var endKey = keys[keys.length - 1];
  50469. if (startKey.frame > beginFrame) {
  50470. var newKey = {
  50471. frame: beginFrame,
  50472. value: startKey.value,
  50473. inTangent: startKey.inTangent,
  50474. outTangent: startKey.outTangent,
  50475. interpolation: startKey.interpolation
  50476. };
  50477. keys.splice(0, 0, newKey);
  50478. }
  50479. if (endKey.frame < endFrame) {
  50480. var newKey = {
  50481. frame: endFrame,
  50482. value: endKey.value,
  50483. inTangent: endKey.outTangent,
  50484. outTangent: endKey.outTangent,
  50485. interpolation: endKey.interpolation
  50486. };
  50487. keys.push(newKey);
  50488. }
  50489. }
  50490. return this;
  50491. };
  50492. /**
  50493. * Start all animations on given targets
  50494. * @param loop defines if animations must loop
  50495. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50496. * @param from defines the from key (optional)
  50497. * @param to defines the to key (optional)
  50498. * @returns the current animation group
  50499. */
  50500. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50501. var _this = this;
  50502. if (loop === void 0) { loop = false; }
  50503. if (speedRatio === void 0) { speedRatio = 1; }
  50504. if (this._isStarted || this._targetedAnimations.length === 0) {
  50505. return this;
  50506. }
  50507. var _loop_1 = function () {
  50508. var targetedAnimation = this_1._targetedAnimations[index];
  50509. if (!targetedAnimation.target.animations) {
  50510. targetedAnimation.target.animations = [];
  50511. }
  50512. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50513. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50514. }
  50515. 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 () {
  50516. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50517. }));
  50518. };
  50519. var this_1 = this;
  50520. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50521. _loop_1();
  50522. }
  50523. this._speedRatio = speedRatio;
  50524. this._isStarted = true;
  50525. return this;
  50526. };
  50527. /**
  50528. * Pause all animations
  50529. */
  50530. AnimationGroup.prototype.pause = function () {
  50531. if (!this._isStarted) {
  50532. return this;
  50533. }
  50534. for (var index = 0; index < this._animatables.length; index++) {
  50535. var animatable = this._animatables[index];
  50536. animatable.pause();
  50537. }
  50538. return this;
  50539. };
  50540. /**
  50541. * Play all animations to initial state
  50542. * This function will start() the animations if they were not started or will restart() them if they were paused
  50543. * @param loop defines if animations must loop
  50544. */
  50545. AnimationGroup.prototype.play = function (loop) {
  50546. if (this.isStarted) {
  50547. if (loop !== undefined) {
  50548. for (var index = 0; index < this._animatables.length; index++) {
  50549. var animatable = this._animatables[index];
  50550. animatable.loopAnimation = loop;
  50551. }
  50552. }
  50553. this.restart();
  50554. }
  50555. else {
  50556. this.start(loop, this._speedRatio);
  50557. }
  50558. return this;
  50559. };
  50560. /**
  50561. * Reset all animations to initial state
  50562. */
  50563. AnimationGroup.prototype.reset = function () {
  50564. if (!this._isStarted) {
  50565. return this;
  50566. }
  50567. for (var index = 0; index < this._animatables.length; index++) {
  50568. var animatable = this._animatables[index];
  50569. animatable.reset();
  50570. }
  50571. return this;
  50572. };
  50573. /**
  50574. * Restart animations from key 0
  50575. */
  50576. AnimationGroup.prototype.restart = function () {
  50577. if (!this._isStarted) {
  50578. return this;
  50579. }
  50580. for (var index = 0; index < this._animatables.length; index++) {
  50581. var animatable = this._animatables[index];
  50582. animatable.restart();
  50583. }
  50584. return this;
  50585. };
  50586. /**
  50587. * Stop all animations
  50588. */
  50589. AnimationGroup.prototype.stop = function () {
  50590. if (!this._isStarted) {
  50591. return this;
  50592. }
  50593. for (var index = 0; index < this._animatables.length; index++) {
  50594. var animatable = this._animatables[index];
  50595. animatable.stop();
  50596. }
  50597. this._isStarted = false;
  50598. return this;
  50599. };
  50600. /**
  50601. * Set animation weight for all animatables
  50602. * @param weight defines the weight to use
  50603. * @return the animationGroup
  50604. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50605. */
  50606. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50607. for (var index = 0; index < this._animatables.length; index++) {
  50608. var animatable = this._animatables[index];
  50609. animatable.weight = weight;
  50610. }
  50611. return this;
  50612. };
  50613. /**
  50614. * Synchronize and normalize all animatables with a source animatable
  50615. * @param root defines the root animatable to synchronize with
  50616. * @return the animationGroup
  50617. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50618. */
  50619. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50620. for (var index = 0; index < this._animatables.length; index++) {
  50621. var animatable = this._animatables[index];
  50622. animatable.syncWith(root);
  50623. }
  50624. return this;
  50625. };
  50626. /**
  50627. * Goes to a specific frame in this animation group
  50628. * @param frame the frame number to go to
  50629. * @return the animationGroup
  50630. */
  50631. AnimationGroup.prototype.goToFrame = function (frame) {
  50632. if (!this._isStarted) {
  50633. return this;
  50634. }
  50635. for (var index = 0; index < this._animatables.length; index++) {
  50636. var animatable = this._animatables[index];
  50637. animatable.goToFrame(frame);
  50638. }
  50639. return this;
  50640. };
  50641. /**
  50642. * Dispose all associated resources
  50643. */
  50644. AnimationGroup.prototype.dispose = function () {
  50645. this._targetedAnimations = [];
  50646. this._animatables = [];
  50647. var index = this._scene.animationGroups.indexOf(this);
  50648. if (index > -1) {
  50649. this._scene.animationGroups.splice(index, 1);
  50650. }
  50651. };
  50652. return AnimationGroup;
  50653. }());
  50654. BABYLON.AnimationGroup = AnimationGroup;
  50655. })(BABYLON || (BABYLON = {}));
  50656. //# sourceMappingURL=babylon.animationGroup.js.map
  50657. var BABYLON;
  50658. (function (BABYLON) {
  50659. var RuntimeAnimation = /** @class */ (function () {
  50660. /**
  50661. * Create a new RuntimeAnimation object
  50662. * @param target defines the target of the animation
  50663. * @param animation defines the source {BABYLON.Animation} object
  50664. * @param scene defines the hosting scene
  50665. * @param host defines the initiating Animatable
  50666. */
  50667. function RuntimeAnimation(target, animation, scene, host) {
  50668. this._currentFrame = 0;
  50669. this._offsetsCache = {};
  50670. this._highLimitsCache = {};
  50671. this._stopped = false;
  50672. this._blendingFactor = 0;
  50673. this._targetPath = "";
  50674. this._weight = 1.0;
  50675. this._ratioOffset = 0;
  50676. this._previousDelay = 0;
  50677. this._previousRatio = 0;
  50678. this._animation = animation;
  50679. this._target = target;
  50680. this._scene = scene;
  50681. this._host = host;
  50682. animation._runtimeAnimations.push(this);
  50683. }
  50684. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50685. /**
  50686. * Gets the current frame
  50687. */
  50688. get: function () {
  50689. return this._currentFrame;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50695. /**
  50696. * Gets the weight of the runtime animation
  50697. */
  50698. get: function () {
  50699. return this._weight;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50705. /**
  50706. * Gets the original value of the runtime animation
  50707. */
  50708. get: function () {
  50709. return this._originalValue;
  50710. },
  50711. enumerable: true,
  50712. configurable: true
  50713. });
  50714. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50715. /**
  50716. * Gets the current value of the runtime animation
  50717. */
  50718. get: function () {
  50719. return this._currentValue;
  50720. },
  50721. enumerable: true,
  50722. configurable: true
  50723. });
  50724. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50725. /**
  50726. * Gets the path where to store the animated value in the target
  50727. */
  50728. get: function () {
  50729. return this._targetPath;
  50730. },
  50731. enumerable: true,
  50732. configurable: true
  50733. });
  50734. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50735. /**
  50736. * Gets the actual target of the runtime animation
  50737. */
  50738. get: function () {
  50739. return this._activeTarget;
  50740. },
  50741. enumerable: true,
  50742. configurable: true
  50743. });
  50744. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50745. get: function () {
  50746. return this._animation;
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. RuntimeAnimation.prototype.reset = function () {
  50752. this._offsetsCache = {};
  50753. this._highLimitsCache = {};
  50754. this._currentFrame = 0;
  50755. this._blendingFactor = 0;
  50756. this._originalValue = null;
  50757. };
  50758. RuntimeAnimation.prototype.isStopped = function () {
  50759. return this._stopped;
  50760. };
  50761. RuntimeAnimation.prototype.dispose = function () {
  50762. var index = this._animation.runtimeAnimations.indexOf(this);
  50763. if (index > -1) {
  50764. this._animation.runtimeAnimations.splice(index, 1);
  50765. }
  50766. };
  50767. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50768. if (typeof value === "function") {
  50769. return value();
  50770. }
  50771. return value;
  50772. };
  50773. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50774. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50775. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50776. }
  50777. this._currentFrame = currentFrame;
  50778. var keys = this._animation.getKeys();
  50779. // Try to get a hash to find the right key
  50780. 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));
  50781. if (keys[startKeyIndex].frame >= currentFrame) {
  50782. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50783. startKeyIndex--;
  50784. }
  50785. }
  50786. for (var key = startKeyIndex; key < keys.length; key++) {
  50787. var endKey = keys[key + 1];
  50788. if (endKey.frame >= currentFrame) {
  50789. var startKey = keys[key];
  50790. var startValue = this._getKeyValue(startKey.value);
  50791. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50792. return startValue;
  50793. }
  50794. var endValue = this._getKeyValue(endKey.value);
  50795. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50796. var frameDelta = endKey.frame - startKey.frame;
  50797. // gradient : percent of currentFrame between the frame inf and the frame sup
  50798. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50799. // check for easingFunction and correction of gradient
  50800. var easingFunction = this._animation.getEasingFunction();
  50801. if (easingFunction != null) {
  50802. gradient = easingFunction.ease(gradient);
  50803. }
  50804. switch (this._animation.dataType) {
  50805. // Float
  50806. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50807. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50808. switch (loopMode) {
  50809. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50810. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50811. return floatValue;
  50812. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50813. return offsetValue * repeatCount + floatValue;
  50814. }
  50815. break;
  50816. // Quaternion
  50817. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50818. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50819. switch (loopMode) {
  50820. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50821. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50822. return quatValue;
  50823. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50824. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50825. }
  50826. return quatValue;
  50827. // Vector3
  50828. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50829. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50830. switch (loopMode) {
  50831. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50832. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50833. return vec3Value;
  50834. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50835. return vec3Value.add(offsetValue.scale(repeatCount));
  50836. }
  50837. // Vector2
  50838. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50839. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50840. switch (loopMode) {
  50841. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50842. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50843. return vec2Value;
  50844. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50845. return vec2Value.add(offsetValue.scale(repeatCount));
  50846. }
  50847. // Size
  50848. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50849. switch (loopMode) {
  50850. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50851. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50852. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50853. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50854. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50855. }
  50856. // Color3
  50857. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50858. switch (loopMode) {
  50859. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50860. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50861. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50862. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50863. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50864. }
  50865. // Matrix
  50866. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50867. switch (loopMode) {
  50868. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50869. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50870. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50871. this._workValue = this._animation.matrixInterpolateFunction(startValue, endValue, gradient, this._workValue);
  50872. return this._workValue;
  50873. }
  50874. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50875. return startValue;
  50876. }
  50877. default:
  50878. break;
  50879. }
  50880. break;
  50881. }
  50882. }
  50883. return this._getKeyValue(keys[keys.length - 1].value);
  50884. };
  50885. /**
  50886. * Affect the interpolated value to the target
  50887. * @param currentValue defines the value computed by the animation
  50888. * @param weight defines the weight to apply to this value
  50889. */
  50890. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50891. if (weight === void 0) { weight = 1.0; }
  50892. if (this._target instanceof Array) {
  50893. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50894. var target = _a[_i];
  50895. this._setValue(target, currentValue, weight);
  50896. }
  50897. }
  50898. else {
  50899. this._setValue(this._target, currentValue, weight);
  50900. }
  50901. };
  50902. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  50903. if (weight === void 0) { weight = 1.0; }
  50904. // Set value
  50905. var path;
  50906. var destination;
  50907. var targetPropertyPath = this._animation.targetPropertyPath;
  50908. if (targetPropertyPath.length > 1) {
  50909. var property = target[targetPropertyPath[0]];
  50910. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50911. property = property[targetPropertyPath[index]];
  50912. }
  50913. path = targetPropertyPath[targetPropertyPath.length - 1];
  50914. destination = property;
  50915. }
  50916. else {
  50917. path = targetPropertyPath[0];
  50918. destination = target;
  50919. }
  50920. this._targetPath = path;
  50921. this._activeTarget = destination;
  50922. this._weight = weight;
  50923. // Blending
  50924. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50925. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50926. if (enableBlending && this._blendingFactor <= 1.0) {
  50927. if (!this._originalBlendValue) {
  50928. var originalValue = destination[path];
  50929. if (originalValue.clone) {
  50930. this._originalBlendValue = originalValue.clone();
  50931. }
  50932. else {
  50933. this._originalBlendValue = originalValue;
  50934. }
  50935. }
  50936. }
  50937. if (weight !== -1.0) {
  50938. if (!this._originalValue) {
  50939. var originalValue = void 0;
  50940. if (destination.getRestPose) { // For bones
  50941. originalValue = destination.getRestPose();
  50942. }
  50943. else {
  50944. originalValue = destination[path];
  50945. }
  50946. if (originalValue.clone) {
  50947. this._originalValue = originalValue.clone();
  50948. }
  50949. else {
  50950. this._originalValue = originalValue;
  50951. }
  50952. }
  50953. }
  50954. if (enableBlending && this._blendingFactor <= 1.0) {
  50955. if (this._originalBlendValue.m) { // Matrix
  50956. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50957. if (this._currentValue) {
  50958. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50959. }
  50960. else {
  50961. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50962. }
  50963. }
  50964. else {
  50965. if (this._currentValue) {
  50966. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50967. }
  50968. else {
  50969. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50970. }
  50971. }
  50972. }
  50973. else if (this._originalBlendValue.constructor) { // Complex value
  50974. var constructor = this._originalBlendValue.constructor;
  50975. if (constructor.Lerp) { // Lerp supported
  50976. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50977. }
  50978. else if (constructor.Slerp) { // Slerp supported
  50979. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50980. }
  50981. else { // Blending not supported
  50982. this._currentValue = currentValue;
  50983. }
  50984. }
  50985. else { // Direct value
  50986. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50987. }
  50988. this._blendingFactor += blendingSpeed;
  50989. }
  50990. else {
  50991. this._currentValue = currentValue;
  50992. }
  50993. if (weight !== -1.0) {
  50994. this._scene._registerTargetForLateAnimationBinding(this);
  50995. }
  50996. else {
  50997. destination[path] = this._currentValue;
  50998. }
  50999. if (target.markAsDirty) {
  51000. target.markAsDirty(this._animation.targetProperty);
  51001. }
  51002. };
  51003. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51004. if (this._target && this._target.animationPropertiesOverride) {
  51005. return this._target.animationPropertiesOverride.loopMode;
  51006. }
  51007. return this._animation.loopMode;
  51008. };
  51009. /**
  51010. * Move the current animation to a given frame
  51011. * @param frame defines the frame to move to
  51012. */
  51013. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51014. var keys = this._animation.getKeys();
  51015. if (frame < keys[0].frame) {
  51016. frame = keys[0].frame;
  51017. }
  51018. else if (frame > keys[keys.length - 1].frame) {
  51019. frame = keys[keys.length - 1].frame;
  51020. }
  51021. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51022. this.setValue(currentValue, -1);
  51023. };
  51024. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51025. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51026. this._ratioOffset = this._previousRatio - newRatio;
  51027. };
  51028. /**
  51029. * Execute the current animation
  51030. * @param delay defines the delay to add to the current frame
  51031. * @param from defines the lower bound of the animation range
  51032. * @param to defines the upper bound of the animation range
  51033. * @param loop defines if the current animation must loop
  51034. * @param speedRatio defines the current speed ratio
  51035. * @param weight defines the weight of the animation (default is -1 so no weight)
  51036. * @returns a boolean indicating if the animation has ended
  51037. */
  51038. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51039. if (weight === void 0) { weight = -1.0; }
  51040. var targetPropertyPath = this._animation.targetPropertyPath;
  51041. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51042. this._stopped = true;
  51043. return false;
  51044. }
  51045. var returnValue = true;
  51046. var keys = this._animation.getKeys();
  51047. // Adding a start key at frame 0 if missing
  51048. if (keys[0].frame !== 0) {
  51049. var newKey = { frame: 0, value: keys[0].value };
  51050. keys.splice(0, 0, newKey);
  51051. }
  51052. // Check limits
  51053. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51054. from = keys[0].frame;
  51055. }
  51056. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51057. to = keys[keys.length - 1].frame;
  51058. }
  51059. //to and from cannot be the same key
  51060. if (from === to) {
  51061. if (from > keys[0].frame) {
  51062. from--;
  51063. }
  51064. else if (to < keys[keys.length - 1].frame) {
  51065. to++;
  51066. }
  51067. }
  51068. // Compute ratio
  51069. var range = to - from;
  51070. var offsetValue;
  51071. // ratio represents the frame delta between from and to
  51072. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51073. var highLimitValue = 0;
  51074. this._previousDelay = delay;
  51075. this._previousRatio = ratio;
  51076. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51077. returnValue = false;
  51078. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  51079. }
  51080. else {
  51081. // Get max value if required
  51082. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51083. var keyOffset = to.toString() + from.toString();
  51084. if (!this._offsetsCache[keyOffset]) {
  51085. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51086. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51087. switch (this._animation.dataType) {
  51088. // Float
  51089. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51090. this._offsetsCache[keyOffset] = toValue - fromValue;
  51091. break;
  51092. // Quaternion
  51093. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51094. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51095. break;
  51096. // Vector3
  51097. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51098. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51099. // Vector2
  51100. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51101. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51102. // Size
  51103. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51104. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51105. // Color3
  51106. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51107. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51108. default:
  51109. break;
  51110. }
  51111. this._highLimitsCache[keyOffset] = toValue;
  51112. }
  51113. highLimitValue = this._highLimitsCache[keyOffset];
  51114. offsetValue = this._offsetsCache[keyOffset];
  51115. }
  51116. }
  51117. if (offsetValue === undefined) {
  51118. switch (this._animation.dataType) {
  51119. // Float
  51120. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51121. offsetValue = 0;
  51122. break;
  51123. // Quaternion
  51124. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51125. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51126. break;
  51127. // Vector3
  51128. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51129. offsetValue = BABYLON.Vector3.Zero();
  51130. break;
  51131. // Vector2
  51132. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51133. offsetValue = BABYLON.Vector2.Zero();
  51134. break;
  51135. // Size
  51136. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51137. offsetValue = BABYLON.Size.Zero();
  51138. break;
  51139. // Color3
  51140. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51141. offsetValue = BABYLON.Color3.Black();
  51142. }
  51143. }
  51144. // Compute value
  51145. var repeatCount = (ratio / range) >> 0;
  51146. var currentFrame = returnValue ? from + ratio % range : to;
  51147. // Need to normalize?
  51148. if (this._host && this._host.syncRoot) {
  51149. var syncRoot = this._host.syncRoot;
  51150. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51151. currentFrame = from + (to - from) * hostNormalizedFrame;
  51152. }
  51153. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51154. // Set value
  51155. this.setValue(currentValue, weight);
  51156. // Check events
  51157. var events = this._animation.getEvents();
  51158. for (var index = 0; index < events.length; index++) {
  51159. // Make sure current frame has passed event frame and that event frame is within the current range
  51160. // Also, handle both forward and reverse animations
  51161. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51162. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51163. var event = events[index];
  51164. if (!event.isDone) {
  51165. // If event should be done only once, remove it.
  51166. if (event.onlyOnce) {
  51167. events.splice(index, 1);
  51168. index--;
  51169. }
  51170. event.isDone = true;
  51171. event.action();
  51172. } // Don't do anything if the event has already be done.
  51173. }
  51174. else if (events[index].isDone && !events[index].onlyOnce) {
  51175. // reset event, the animation is looping
  51176. events[index].isDone = false;
  51177. }
  51178. }
  51179. if (!returnValue) {
  51180. this._stopped = true;
  51181. }
  51182. return returnValue;
  51183. };
  51184. return RuntimeAnimation;
  51185. }());
  51186. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51187. })(BABYLON || (BABYLON = {}));
  51188. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51189. var BABYLON;
  51190. (function (BABYLON) {
  51191. var Animatable = /** @class */ (function () {
  51192. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51193. if (fromFrame === void 0) { fromFrame = 0; }
  51194. if (toFrame === void 0) { toFrame = 100; }
  51195. if (loopAnimation === void 0) { loopAnimation = false; }
  51196. if (speedRatio === void 0) { speedRatio = 1.0; }
  51197. this.target = target;
  51198. this.fromFrame = fromFrame;
  51199. this.toFrame = toFrame;
  51200. this.loopAnimation = loopAnimation;
  51201. this.onAnimationEnd = onAnimationEnd;
  51202. this._localDelayOffset = null;
  51203. this._pausedDelay = null;
  51204. this._runtimeAnimations = new Array();
  51205. this._paused = false;
  51206. this._speedRatio = 1;
  51207. this._weight = -1.0;
  51208. this.animationStarted = false;
  51209. this._scene = scene;
  51210. if (animations) {
  51211. this.appendAnimations(target, animations);
  51212. }
  51213. this._speedRatio = speedRatio;
  51214. scene._activeAnimatables.push(this);
  51215. }
  51216. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51217. /**
  51218. * Gets the root Animatable used to synchronize and normalize animations
  51219. */
  51220. get: function () {
  51221. return this._syncRoot;
  51222. },
  51223. enumerable: true,
  51224. configurable: true
  51225. });
  51226. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51227. /**
  51228. * Gets the current frame of the first RuntimeAnimation
  51229. * Used to synchronize Animatables
  51230. */
  51231. get: function () {
  51232. if (this._runtimeAnimations.length === 0) {
  51233. return 0;
  51234. }
  51235. return this._runtimeAnimations[0].currentFrame;
  51236. },
  51237. enumerable: true,
  51238. configurable: true
  51239. });
  51240. Object.defineProperty(Animatable.prototype, "weight", {
  51241. /**
  51242. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51243. */
  51244. get: function () {
  51245. return this._weight;
  51246. },
  51247. set: function (value) {
  51248. if (value === -1) { // -1 is ok and means no weight
  51249. this._weight = -1;
  51250. return;
  51251. }
  51252. // Else weight must be in [0, 1] range
  51253. this._weight = Math.min(Math.max(value, 0), 1.0);
  51254. },
  51255. enumerable: true,
  51256. configurable: true
  51257. });
  51258. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51259. /**
  51260. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51261. */
  51262. get: function () {
  51263. return this._speedRatio;
  51264. },
  51265. set: function (value) {
  51266. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51267. var animation = this._runtimeAnimations[index];
  51268. animation._prepareForSpeedRatioChange(value);
  51269. }
  51270. this._speedRatio = value;
  51271. },
  51272. enumerable: true,
  51273. configurable: true
  51274. });
  51275. // Methods
  51276. /**
  51277. * Synchronize and normalize current Animatable with a source Animatable
  51278. * This is useful when using animation weights and when animations are not of the same length
  51279. * @param root defines the root Animatable to synchronize with
  51280. * @returns the current Animatable
  51281. */
  51282. Animatable.prototype.syncWith = function (root) {
  51283. this._syncRoot = root;
  51284. if (root) {
  51285. // Make sure this animatable will animate after the root
  51286. var index = this._scene._activeAnimatables.indexOf(this);
  51287. if (index > -1) {
  51288. this._scene._activeAnimatables.splice(index, 1);
  51289. this._scene._activeAnimatables.push(this);
  51290. }
  51291. }
  51292. return this;
  51293. };
  51294. Animatable.prototype.getAnimations = function () {
  51295. return this._runtimeAnimations;
  51296. };
  51297. Animatable.prototype.appendAnimations = function (target, animations) {
  51298. for (var index = 0; index < animations.length; index++) {
  51299. var animation = animations[index];
  51300. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51301. }
  51302. };
  51303. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51304. var runtimeAnimations = this._runtimeAnimations;
  51305. for (var index = 0; index < runtimeAnimations.length; index++) {
  51306. if (runtimeAnimations[index].animation.targetProperty === property) {
  51307. return runtimeAnimations[index].animation;
  51308. }
  51309. }
  51310. return null;
  51311. };
  51312. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51313. var runtimeAnimations = this._runtimeAnimations;
  51314. for (var index = 0; index < runtimeAnimations.length; index++) {
  51315. if (runtimeAnimations[index].animation.targetProperty === property) {
  51316. return runtimeAnimations[index];
  51317. }
  51318. }
  51319. return null;
  51320. };
  51321. Animatable.prototype.reset = function () {
  51322. var runtimeAnimations = this._runtimeAnimations;
  51323. for (var index = 0; index < runtimeAnimations.length; index++) {
  51324. runtimeAnimations[index].reset();
  51325. }
  51326. // Reset to original value
  51327. for (index = 0; index < runtimeAnimations.length; index++) {
  51328. var animation = runtimeAnimations[index];
  51329. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51330. }
  51331. this._localDelayOffset = null;
  51332. this._pausedDelay = null;
  51333. };
  51334. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51335. var runtimeAnimations = this._runtimeAnimations;
  51336. for (var index = 0; index < runtimeAnimations.length; index++) {
  51337. runtimeAnimations[index].animation.enableBlending = true;
  51338. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51339. }
  51340. };
  51341. Animatable.prototype.disableBlending = function () {
  51342. var runtimeAnimations = this._runtimeAnimations;
  51343. for (var index = 0; index < runtimeAnimations.length; index++) {
  51344. runtimeAnimations[index].animation.enableBlending = false;
  51345. }
  51346. };
  51347. Animatable.prototype.goToFrame = function (frame) {
  51348. var runtimeAnimations = this._runtimeAnimations;
  51349. if (runtimeAnimations[0]) {
  51350. var fps = runtimeAnimations[0].animation.framePerSecond;
  51351. var currentFrame = runtimeAnimations[0].currentFrame;
  51352. var adjustTime = frame - currentFrame;
  51353. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51354. if (this._localDelayOffset === null) {
  51355. this._localDelayOffset = 0;
  51356. }
  51357. this._localDelayOffset -= delay;
  51358. }
  51359. for (var index = 0; index < runtimeAnimations.length; index++) {
  51360. runtimeAnimations[index].goToFrame(frame);
  51361. }
  51362. };
  51363. Animatable.prototype.pause = function () {
  51364. if (this._paused) {
  51365. return;
  51366. }
  51367. this._paused = true;
  51368. };
  51369. Animatable.prototype.restart = function () {
  51370. this._paused = false;
  51371. };
  51372. Animatable.prototype.stop = function (animationName) {
  51373. if (animationName) {
  51374. var idx = this._scene._activeAnimatables.indexOf(this);
  51375. if (idx > -1) {
  51376. var runtimeAnimations = this._runtimeAnimations;
  51377. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51378. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51379. continue;
  51380. }
  51381. runtimeAnimations[index].dispose();
  51382. runtimeAnimations.splice(index, 1);
  51383. }
  51384. if (runtimeAnimations.length == 0) {
  51385. this._scene._activeAnimatables.splice(idx, 1);
  51386. if (this.onAnimationEnd) {
  51387. this.onAnimationEnd();
  51388. }
  51389. }
  51390. }
  51391. }
  51392. else {
  51393. var index = this._scene._activeAnimatables.indexOf(this);
  51394. if (index > -1) {
  51395. this._scene._activeAnimatables.splice(index, 1);
  51396. var runtimeAnimations = this._runtimeAnimations;
  51397. for (var index = 0; index < runtimeAnimations.length; index++) {
  51398. runtimeAnimations[index].dispose();
  51399. }
  51400. if (this.onAnimationEnd) {
  51401. this.onAnimationEnd();
  51402. }
  51403. }
  51404. }
  51405. };
  51406. Animatable.prototype._animate = function (delay) {
  51407. if (this._paused) {
  51408. this.animationStarted = false;
  51409. if (this._pausedDelay === null) {
  51410. this._pausedDelay = delay;
  51411. }
  51412. return true;
  51413. }
  51414. if (this._localDelayOffset === null) {
  51415. this._localDelayOffset = delay;
  51416. this._pausedDelay = null;
  51417. }
  51418. else if (this._pausedDelay !== null) {
  51419. this._localDelayOffset += delay - this._pausedDelay;
  51420. this._pausedDelay = null;
  51421. }
  51422. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51423. return true;
  51424. }
  51425. // Animating
  51426. var running = false;
  51427. var runtimeAnimations = this._runtimeAnimations;
  51428. var index;
  51429. for (index = 0; index < runtimeAnimations.length; index++) {
  51430. var animation = runtimeAnimations[index];
  51431. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51432. running = running || isRunning;
  51433. }
  51434. this.animationStarted = running;
  51435. if (!running) {
  51436. // Remove from active animatables
  51437. index = this._scene._activeAnimatables.indexOf(this);
  51438. this._scene._activeAnimatables.splice(index, 1);
  51439. // Dispose all runtime animations
  51440. for (index = 0; index < runtimeAnimations.length; index++) {
  51441. runtimeAnimations[index].dispose();
  51442. }
  51443. }
  51444. if (!running && this.onAnimationEnd) {
  51445. this.onAnimationEnd();
  51446. this.onAnimationEnd = null;
  51447. }
  51448. return running;
  51449. };
  51450. return Animatable;
  51451. }());
  51452. BABYLON.Animatable = Animatable;
  51453. })(BABYLON || (BABYLON = {}));
  51454. //# sourceMappingURL=babylon.animatable.js.map
  51455. var BABYLON;
  51456. (function (BABYLON) {
  51457. var EasingFunction = /** @class */ (function () {
  51458. function EasingFunction() {
  51459. // Properties
  51460. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51461. }
  51462. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51463. get: function () {
  51464. return EasingFunction._EASINGMODE_EASEIN;
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51470. get: function () {
  51471. return EasingFunction._EASINGMODE_EASEOUT;
  51472. },
  51473. enumerable: true,
  51474. configurable: true
  51475. });
  51476. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51477. get: function () {
  51478. return EasingFunction._EASINGMODE_EASEINOUT;
  51479. },
  51480. enumerable: true,
  51481. configurable: true
  51482. });
  51483. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51484. var n = Math.min(Math.max(easingMode, 0), 2);
  51485. this._easingMode = n;
  51486. };
  51487. EasingFunction.prototype.getEasingMode = function () {
  51488. return this._easingMode;
  51489. };
  51490. EasingFunction.prototype.easeInCore = function (gradient) {
  51491. throw new Error('You must implement this method');
  51492. };
  51493. EasingFunction.prototype.ease = function (gradient) {
  51494. switch (this._easingMode) {
  51495. case EasingFunction.EASINGMODE_EASEIN:
  51496. return this.easeInCore(gradient);
  51497. case EasingFunction.EASINGMODE_EASEOUT:
  51498. return (1 - this.easeInCore(1 - gradient));
  51499. }
  51500. if (gradient >= 0.5) {
  51501. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51502. }
  51503. return (this.easeInCore(gradient * 2) * 0.5);
  51504. };
  51505. //Statics
  51506. EasingFunction._EASINGMODE_EASEIN = 0;
  51507. EasingFunction._EASINGMODE_EASEOUT = 1;
  51508. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51509. return EasingFunction;
  51510. }());
  51511. BABYLON.EasingFunction = EasingFunction;
  51512. var CircleEase = /** @class */ (function (_super) {
  51513. __extends(CircleEase, _super);
  51514. function CircleEase() {
  51515. return _super !== null && _super.apply(this, arguments) || this;
  51516. }
  51517. CircleEase.prototype.easeInCore = function (gradient) {
  51518. gradient = Math.max(0, Math.min(1, gradient));
  51519. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51520. };
  51521. return CircleEase;
  51522. }(EasingFunction));
  51523. BABYLON.CircleEase = CircleEase;
  51524. var BackEase = /** @class */ (function (_super) {
  51525. __extends(BackEase, _super);
  51526. function BackEase(amplitude) {
  51527. if (amplitude === void 0) { amplitude = 1; }
  51528. var _this = _super.call(this) || this;
  51529. _this.amplitude = amplitude;
  51530. return _this;
  51531. }
  51532. BackEase.prototype.easeInCore = function (gradient) {
  51533. var num = Math.max(0, this.amplitude);
  51534. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51535. };
  51536. return BackEase;
  51537. }(EasingFunction));
  51538. BABYLON.BackEase = BackEase;
  51539. var BounceEase = /** @class */ (function (_super) {
  51540. __extends(BounceEase, _super);
  51541. function BounceEase(bounces, bounciness) {
  51542. if (bounces === void 0) { bounces = 3; }
  51543. if (bounciness === void 0) { bounciness = 2; }
  51544. var _this = _super.call(this) || this;
  51545. _this.bounces = bounces;
  51546. _this.bounciness = bounciness;
  51547. return _this;
  51548. }
  51549. BounceEase.prototype.easeInCore = function (gradient) {
  51550. var y = Math.max(0.0, this.bounces);
  51551. var bounciness = this.bounciness;
  51552. if (bounciness <= 1.0) {
  51553. bounciness = 1.001;
  51554. }
  51555. var num9 = Math.pow(bounciness, y);
  51556. var num5 = 1.0 - bounciness;
  51557. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51558. var num15 = gradient * num4;
  51559. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51560. var num3 = Math.floor(num65);
  51561. var num13 = num3 + 1.0;
  51562. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51563. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51564. var num7 = (num8 + num12) * 0.5;
  51565. var num6 = gradient - num7;
  51566. var num2 = num7 - num8;
  51567. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51568. };
  51569. return BounceEase;
  51570. }(EasingFunction));
  51571. BABYLON.BounceEase = BounceEase;
  51572. var CubicEase = /** @class */ (function (_super) {
  51573. __extends(CubicEase, _super);
  51574. function CubicEase() {
  51575. return _super !== null && _super.apply(this, arguments) || this;
  51576. }
  51577. CubicEase.prototype.easeInCore = function (gradient) {
  51578. return (gradient * gradient * gradient);
  51579. };
  51580. return CubicEase;
  51581. }(EasingFunction));
  51582. BABYLON.CubicEase = CubicEase;
  51583. var ElasticEase = /** @class */ (function (_super) {
  51584. __extends(ElasticEase, _super);
  51585. function ElasticEase(oscillations, springiness) {
  51586. if (oscillations === void 0) { oscillations = 3; }
  51587. if (springiness === void 0) { springiness = 3; }
  51588. var _this = _super.call(this) || this;
  51589. _this.oscillations = oscillations;
  51590. _this.springiness = springiness;
  51591. return _this;
  51592. }
  51593. ElasticEase.prototype.easeInCore = function (gradient) {
  51594. var num2;
  51595. var num3 = Math.max(0.0, this.oscillations);
  51596. var num = Math.max(0.0, this.springiness);
  51597. if (num == 0) {
  51598. num2 = gradient;
  51599. }
  51600. else {
  51601. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51602. }
  51603. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51604. };
  51605. return ElasticEase;
  51606. }(EasingFunction));
  51607. BABYLON.ElasticEase = ElasticEase;
  51608. var ExponentialEase = /** @class */ (function (_super) {
  51609. __extends(ExponentialEase, _super);
  51610. function ExponentialEase(exponent) {
  51611. if (exponent === void 0) { exponent = 2; }
  51612. var _this = _super.call(this) || this;
  51613. _this.exponent = exponent;
  51614. return _this;
  51615. }
  51616. ExponentialEase.prototype.easeInCore = function (gradient) {
  51617. if (this.exponent <= 0) {
  51618. return gradient;
  51619. }
  51620. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51621. };
  51622. return ExponentialEase;
  51623. }(EasingFunction));
  51624. BABYLON.ExponentialEase = ExponentialEase;
  51625. var PowerEase = /** @class */ (function (_super) {
  51626. __extends(PowerEase, _super);
  51627. function PowerEase(power) {
  51628. if (power === void 0) { power = 2; }
  51629. var _this = _super.call(this) || this;
  51630. _this.power = power;
  51631. return _this;
  51632. }
  51633. PowerEase.prototype.easeInCore = function (gradient) {
  51634. var y = Math.max(0.0, this.power);
  51635. return Math.pow(gradient, y);
  51636. };
  51637. return PowerEase;
  51638. }(EasingFunction));
  51639. BABYLON.PowerEase = PowerEase;
  51640. var QuadraticEase = /** @class */ (function (_super) {
  51641. __extends(QuadraticEase, _super);
  51642. function QuadraticEase() {
  51643. return _super !== null && _super.apply(this, arguments) || this;
  51644. }
  51645. QuadraticEase.prototype.easeInCore = function (gradient) {
  51646. return (gradient * gradient);
  51647. };
  51648. return QuadraticEase;
  51649. }(EasingFunction));
  51650. BABYLON.QuadraticEase = QuadraticEase;
  51651. var QuarticEase = /** @class */ (function (_super) {
  51652. __extends(QuarticEase, _super);
  51653. function QuarticEase() {
  51654. return _super !== null && _super.apply(this, arguments) || this;
  51655. }
  51656. QuarticEase.prototype.easeInCore = function (gradient) {
  51657. return (gradient * gradient * gradient * gradient);
  51658. };
  51659. return QuarticEase;
  51660. }(EasingFunction));
  51661. BABYLON.QuarticEase = QuarticEase;
  51662. var QuinticEase = /** @class */ (function (_super) {
  51663. __extends(QuinticEase, _super);
  51664. function QuinticEase() {
  51665. return _super !== null && _super.apply(this, arguments) || this;
  51666. }
  51667. QuinticEase.prototype.easeInCore = function (gradient) {
  51668. return (gradient * gradient * gradient * gradient * gradient);
  51669. };
  51670. return QuinticEase;
  51671. }(EasingFunction));
  51672. BABYLON.QuinticEase = QuinticEase;
  51673. var SineEase = /** @class */ (function (_super) {
  51674. __extends(SineEase, _super);
  51675. function SineEase() {
  51676. return _super !== null && _super.apply(this, arguments) || this;
  51677. }
  51678. SineEase.prototype.easeInCore = function (gradient) {
  51679. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51680. };
  51681. return SineEase;
  51682. }(EasingFunction));
  51683. BABYLON.SineEase = SineEase;
  51684. var BezierCurveEase = /** @class */ (function (_super) {
  51685. __extends(BezierCurveEase, _super);
  51686. function BezierCurveEase(x1, y1, x2, y2) {
  51687. if (x1 === void 0) { x1 = 0; }
  51688. if (y1 === void 0) { y1 = 0; }
  51689. if (x2 === void 0) { x2 = 1; }
  51690. if (y2 === void 0) { y2 = 1; }
  51691. var _this = _super.call(this) || this;
  51692. _this.x1 = x1;
  51693. _this.y1 = y1;
  51694. _this.x2 = x2;
  51695. _this.y2 = y2;
  51696. return _this;
  51697. }
  51698. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51699. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51700. };
  51701. return BezierCurveEase;
  51702. }(EasingFunction));
  51703. BABYLON.BezierCurveEase = BezierCurveEase;
  51704. })(BABYLON || (BABYLON = {}));
  51705. //# sourceMappingURL=babylon.easing.js.map
  51706. var BABYLON;
  51707. (function (BABYLON) {
  51708. /**
  51709. * A Condition applied to an Action
  51710. */
  51711. var Condition = /** @class */ (function () {
  51712. /**
  51713. * Creates a new Condition
  51714. * @param actionManager the manager of the action the condition is applied to
  51715. */
  51716. function Condition(actionManager) {
  51717. this._actionManager = actionManager;
  51718. }
  51719. /**
  51720. * Check if the current condition is valid
  51721. * @returns a boolean
  51722. */
  51723. Condition.prototype.isValid = function () {
  51724. return true;
  51725. };
  51726. /**
  51727. * Internal only
  51728. * @ignore
  51729. */
  51730. Condition.prototype._getProperty = function (propertyPath) {
  51731. return this._actionManager._getProperty(propertyPath);
  51732. };
  51733. /**
  51734. * Internal only
  51735. * @ignore
  51736. */
  51737. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51738. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51739. };
  51740. /**
  51741. * Serialize placeholder for child classes
  51742. * @returns the serialized object
  51743. */
  51744. Condition.prototype.serialize = function () {
  51745. };
  51746. /**
  51747. * Internal only
  51748. * @ignore
  51749. */
  51750. Condition.prototype._serialize = function (serializedCondition) {
  51751. return {
  51752. type: 2,
  51753. children: [],
  51754. name: serializedCondition.name,
  51755. properties: serializedCondition.properties
  51756. };
  51757. };
  51758. return Condition;
  51759. }());
  51760. BABYLON.Condition = Condition;
  51761. /**
  51762. * Defines specific conditional operators as extensions of Condition
  51763. */
  51764. var ValueCondition = /** @class */ (function (_super) {
  51765. __extends(ValueCondition, _super);
  51766. /**
  51767. * Creates a new ValueCondition
  51768. * @param actionManager manager for the action the condition applies to
  51769. * @param target for the action
  51770. * @param propertyPath path to specify the property of the target the conditional operator uses
  51771. * @param value the vale compared by the conditional operator against the current value of the property
  51772. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51773. */
  51774. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51775. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51776. var _this = _super.call(this, actionManager) || this;
  51777. _this.propertyPath = propertyPath;
  51778. _this.value = value;
  51779. _this.operator = operator;
  51780. _this._target = target;
  51781. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51782. _this._property = _this._getProperty(_this.propertyPath);
  51783. return _this;
  51784. }
  51785. Object.defineProperty(ValueCondition, "IsEqual", {
  51786. /**
  51787. * returns the number for IsEqual
  51788. */
  51789. get: function () {
  51790. return ValueCondition._IsEqual;
  51791. },
  51792. enumerable: true,
  51793. configurable: true
  51794. });
  51795. Object.defineProperty(ValueCondition, "IsDifferent", {
  51796. /**
  51797. * Returns the number for IsDifferent
  51798. */
  51799. get: function () {
  51800. return ValueCondition._IsDifferent;
  51801. },
  51802. enumerable: true,
  51803. configurable: true
  51804. });
  51805. Object.defineProperty(ValueCondition, "IsGreater", {
  51806. /**
  51807. * Returns the number for IsGreater
  51808. */
  51809. get: function () {
  51810. return ValueCondition._IsGreater;
  51811. },
  51812. enumerable: true,
  51813. configurable: true
  51814. });
  51815. Object.defineProperty(ValueCondition, "IsLesser", {
  51816. /**
  51817. * Returns the number for IsLesser
  51818. */
  51819. get: function () {
  51820. return ValueCondition._IsLesser;
  51821. },
  51822. enumerable: true,
  51823. configurable: true
  51824. });
  51825. /**
  51826. * Compares the given value with the property value for the specified conditional operator
  51827. * @returns the result of the comparison
  51828. */
  51829. ValueCondition.prototype.isValid = function () {
  51830. switch (this.operator) {
  51831. case ValueCondition.IsGreater:
  51832. return this._effectiveTarget[this._property] > this.value;
  51833. case ValueCondition.IsLesser:
  51834. return this._effectiveTarget[this._property] < this.value;
  51835. case ValueCondition.IsEqual:
  51836. case ValueCondition.IsDifferent:
  51837. var check;
  51838. if (this.value.equals) {
  51839. check = this.value.equals(this._effectiveTarget[this._property]);
  51840. }
  51841. else {
  51842. check = this.value === this._effectiveTarget[this._property];
  51843. }
  51844. return this.operator === ValueCondition.IsEqual ? check : !check;
  51845. }
  51846. return false;
  51847. };
  51848. /**
  51849. * Serialize the ValueCondition into a JSON compatible object
  51850. * @returns serialization object
  51851. */
  51852. ValueCondition.prototype.serialize = function () {
  51853. return this._serialize({
  51854. name: "ValueCondition",
  51855. properties: [
  51856. BABYLON.Action._GetTargetProperty(this._target),
  51857. { name: "propertyPath", value: this.propertyPath },
  51858. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51859. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51860. ]
  51861. });
  51862. };
  51863. /**
  51864. * Gets the name of the conditional operator for the ValueCondition
  51865. * @param operator the conditional operator
  51866. * @returns the name
  51867. */
  51868. ValueCondition.GetOperatorName = function (operator) {
  51869. switch (operator) {
  51870. case ValueCondition._IsEqual: return "IsEqual";
  51871. case ValueCondition._IsDifferent: return "IsDifferent";
  51872. case ValueCondition._IsGreater: return "IsGreater";
  51873. case ValueCondition._IsLesser: return "IsLesser";
  51874. default: return "";
  51875. }
  51876. };
  51877. /**
  51878. * Internal only
  51879. * @ignore
  51880. */
  51881. ValueCondition._IsEqual = 0;
  51882. /**
  51883. * Internal only
  51884. * @ignore
  51885. */
  51886. ValueCondition._IsDifferent = 1;
  51887. /**
  51888. * Internal only
  51889. * @ignore
  51890. */
  51891. ValueCondition._IsGreater = 2;
  51892. /**
  51893. * Internal only
  51894. * @ignore
  51895. */
  51896. ValueCondition._IsLesser = 3;
  51897. return ValueCondition;
  51898. }(Condition));
  51899. BABYLON.ValueCondition = ValueCondition;
  51900. /**
  51901. * Defines a predicate condition as an extension of Condition
  51902. */
  51903. var PredicateCondition = /** @class */ (function (_super) {
  51904. __extends(PredicateCondition, _super);
  51905. /**
  51906. * Creates a new {BABYLON.PredicateCondition}
  51907. * @param actionManager manager for the action the condition applies to
  51908. * @param predicate
  51909. */
  51910. function PredicateCondition(actionManager, predicate) {
  51911. var _this = _super.call(this, actionManager) || this;
  51912. _this.predicate = predicate;
  51913. return _this;
  51914. }
  51915. /**
  51916. * @returns the validity of the predicate condition
  51917. */
  51918. PredicateCondition.prototype.isValid = function () {
  51919. return this.predicate();
  51920. };
  51921. return PredicateCondition;
  51922. }(Condition));
  51923. BABYLON.PredicateCondition = PredicateCondition;
  51924. /**
  51925. * Defines a state condition as an extension of {BABYLON.Condition}
  51926. */
  51927. var StateCondition = /** @class */ (function (_super) {
  51928. __extends(StateCondition, _super);
  51929. /**
  51930. * Creates a new {BABYLON.StateCondition}
  51931. * @param actionManager manager for the action the condition applies to
  51932. * @param target of the condition
  51933. * @param value to compare with target state
  51934. */
  51935. function StateCondition(actionManager, target, value) {
  51936. var _this = _super.call(this, actionManager) || this;
  51937. _this.value = value;
  51938. _this._target = target;
  51939. return _this;
  51940. }
  51941. /**
  51942. * @returns the validity of the state
  51943. */
  51944. StateCondition.prototype.isValid = function () {
  51945. return this._target.state === this.value;
  51946. };
  51947. /**
  51948. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51949. * @returns serialization object
  51950. */
  51951. StateCondition.prototype.serialize = function () {
  51952. return this._serialize({
  51953. name: "StateCondition",
  51954. properties: [
  51955. BABYLON.Action._GetTargetProperty(this._target),
  51956. { name: "value", value: this.value }
  51957. ]
  51958. });
  51959. };
  51960. return StateCondition;
  51961. }(Condition));
  51962. BABYLON.StateCondition = StateCondition;
  51963. })(BABYLON || (BABYLON = {}));
  51964. //# sourceMappingURL=babylon.condition.js.map
  51965. var BABYLON;
  51966. (function (BABYLON) {
  51967. /**
  51968. * The action to be carried out following a trigger
  51969. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51970. */
  51971. var Action = /** @class */ (function () {
  51972. /**
  51973. * Creates a new Action
  51974. * @param triggerOptions the trigger, with or without parameters, for the action
  51975. * @param condition an optional determinant of action
  51976. */
  51977. function Action(triggerOptions, condition) {
  51978. this.triggerOptions = triggerOptions;
  51979. /**
  51980. * An event triggered prior to action being executed.
  51981. */
  51982. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51983. if (triggerOptions.parameter) {
  51984. this.trigger = triggerOptions.trigger;
  51985. this._triggerParameter = triggerOptions.parameter;
  51986. }
  51987. else {
  51988. this.trigger = triggerOptions;
  51989. }
  51990. this._nextActiveAction = this;
  51991. this._condition = condition;
  51992. }
  51993. /**
  51994. * Internal only
  51995. * @ignore
  51996. */
  51997. Action.prototype._prepare = function () {
  51998. };
  51999. /**
  52000. * Gets the trigger parameters
  52001. * @returns the trigger parameters
  52002. */
  52003. Action.prototype.getTriggerParameter = function () {
  52004. return this._triggerParameter;
  52005. };
  52006. /**
  52007. * Internal only - executes current action event
  52008. * @ignore
  52009. */
  52010. Action.prototype._executeCurrent = function (evt) {
  52011. if (this._nextActiveAction._condition) {
  52012. var condition = this._nextActiveAction._condition;
  52013. var currentRenderId = this._actionManager.getScene().getRenderId();
  52014. // We cache the current evaluation for the current frame
  52015. if (condition._evaluationId === currentRenderId) {
  52016. if (!condition._currentResult) {
  52017. return;
  52018. }
  52019. }
  52020. else {
  52021. condition._evaluationId = currentRenderId;
  52022. if (!condition.isValid()) {
  52023. condition._currentResult = false;
  52024. return;
  52025. }
  52026. condition._currentResult = true;
  52027. }
  52028. }
  52029. this.onBeforeExecuteObservable.notifyObservers(this);
  52030. this._nextActiveAction.execute(evt);
  52031. this.skipToNextActiveAction();
  52032. };
  52033. /**
  52034. * Execute placeholder for child classes
  52035. * @param evt optional action event
  52036. */
  52037. Action.prototype.execute = function (evt) {
  52038. };
  52039. /**
  52040. * Skips to next active action
  52041. */
  52042. Action.prototype.skipToNextActiveAction = function () {
  52043. if (this._nextActiveAction._child) {
  52044. if (!this._nextActiveAction._child._actionManager) {
  52045. this._nextActiveAction._child._actionManager = this._actionManager;
  52046. }
  52047. this._nextActiveAction = this._nextActiveAction._child;
  52048. }
  52049. else {
  52050. this._nextActiveAction = this;
  52051. }
  52052. };
  52053. /**
  52054. * Adds action to chain of actions, may be a DoNothingAction
  52055. * @param index The index of the attribute.
  52056. * @returns The action passed in
  52057. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52058. */
  52059. Action.prototype.then = function (action) {
  52060. this._child = action;
  52061. action._actionManager = this._actionManager;
  52062. action._prepare();
  52063. return action;
  52064. };
  52065. /**
  52066. * Internal only
  52067. * @ignore
  52068. */
  52069. Action.prototype._getProperty = function (propertyPath) {
  52070. return this._actionManager._getProperty(propertyPath);
  52071. };
  52072. /**
  52073. * Internal only
  52074. * @ignore
  52075. */
  52076. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52077. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52078. };
  52079. /**
  52080. * Serialize placeholder for child classes
  52081. * @param parent of child
  52082. * @returns the serialized object
  52083. */
  52084. Action.prototype.serialize = function (parent) {
  52085. };
  52086. /**
  52087. * Internal only called by serialize
  52088. * @ignore
  52089. */
  52090. Action.prototype._serialize = function (serializedAction, parent) {
  52091. var serializationObject = {
  52092. type: 1,
  52093. children: [],
  52094. name: serializedAction.name,
  52095. properties: serializedAction.properties || []
  52096. };
  52097. // Serialize child
  52098. if (this._child) {
  52099. this._child.serialize(serializationObject);
  52100. }
  52101. // Check if "this" has a condition
  52102. if (this._condition) {
  52103. var serializedCondition = this._condition.serialize();
  52104. serializedCondition.children.push(serializationObject);
  52105. if (parent) {
  52106. parent.children.push(serializedCondition);
  52107. }
  52108. return serializedCondition;
  52109. }
  52110. if (parent) {
  52111. parent.children.push(serializationObject);
  52112. }
  52113. return serializationObject;
  52114. };
  52115. /**
  52116. * Internal only
  52117. * @ignore
  52118. */
  52119. Action._SerializeValueAsString = function (value) {
  52120. if (typeof value === "number") {
  52121. return value.toString();
  52122. }
  52123. if (typeof value === "boolean") {
  52124. return value ? "true" : "false";
  52125. }
  52126. if (value instanceof BABYLON.Vector2) {
  52127. return value.x + ", " + value.y;
  52128. }
  52129. if (value instanceof BABYLON.Vector3) {
  52130. return value.x + ", " + value.y + ", " + value.z;
  52131. }
  52132. if (value instanceof BABYLON.Color3) {
  52133. return value.r + ", " + value.g + ", " + value.b;
  52134. }
  52135. if (value instanceof BABYLON.Color4) {
  52136. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52137. }
  52138. return value; // string
  52139. };
  52140. /**
  52141. * Internal only
  52142. * @ignore
  52143. */
  52144. Action._GetTargetProperty = function (target) {
  52145. return {
  52146. name: "target",
  52147. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52148. : target instanceof BABYLON.Light ? "LightProperties"
  52149. : target instanceof BABYLON.Camera ? "CameraProperties"
  52150. : "SceneProperties",
  52151. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52152. };
  52153. };
  52154. return Action;
  52155. }());
  52156. BABYLON.Action = Action;
  52157. })(BABYLON || (BABYLON = {}));
  52158. //# sourceMappingURL=babylon.action.js.map
  52159. var BABYLON;
  52160. (function (BABYLON) {
  52161. /**
  52162. * ActionEvent is the event being sent when an action is triggered.
  52163. */
  52164. var ActionEvent = /** @class */ (function () {
  52165. /**
  52166. * @param source The mesh or sprite that triggered the action.
  52167. * @param pointerX The X mouse cursor position at the time of the event
  52168. * @param pointerY The Y mouse cursor position at the time of the event
  52169. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52170. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52171. */
  52172. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52173. this.source = source;
  52174. this.pointerX = pointerX;
  52175. this.pointerY = pointerY;
  52176. this.meshUnderPointer = meshUnderPointer;
  52177. this.sourceEvent = sourceEvent;
  52178. this.additionalData = additionalData;
  52179. }
  52180. /**
  52181. * Helper function to auto-create an ActionEvent from a source mesh.
  52182. * @param source The source mesh that triggered the event
  52183. * @param evt {Event} The original (browser) event
  52184. */
  52185. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52186. var scene = source.getScene();
  52187. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52188. };
  52189. /**
  52190. * Helper function to auto-create an ActionEvent from a source mesh.
  52191. * @param source The source sprite that triggered the event
  52192. * @param scene Scene associated with the sprite
  52193. * @param evt {Event} The original (browser) event
  52194. */
  52195. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52196. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52197. };
  52198. /**
  52199. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52200. * @param scene the scene where the event occurred
  52201. * @param evt {Event} The original (browser) event
  52202. */
  52203. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52204. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52205. };
  52206. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52207. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52208. };
  52209. return ActionEvent;
  52210. }());
  52211. BABYLON.ActionEvent = ActionEvent;
  52212. /**
  52213. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52214. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52215. */
  52216. var ActionManager = /** @class */ (function () {
  52217. function ActionManager(scene) {
  52218. // Members
  52219. this.actions = new Array();
  52220. this.hoverCursor = '';
  52221. this._scene = scene;
  52222. scene._actionManagers.push(this);
  52223. }
  52224. Object.defineProperty(ActionManager, "NothingTrigger", {
  52225. get: function () {
  52226. return ActionManager._NothingTrigger;
  52227. },
  52228. enumerable: true,
  52229. configurable: true
  52230. });
  52231. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52232. get: function () {
  52233. return ActionManager._OnPickTrigger;
  52234. },
  52235. enumerable: true,
  52236. configurable: true
  52237. });
  52238. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52239. get: function () {
  52240. return ActionManager._OnLeftPickTrigger;
  52241. },
  52242. enumerable: true,
  52243. configurable: true
  52244. });
  52245. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52246. get: function () {
  52247. return ActionManager._OnRightPickTrigger;
  52248. },
  52249. enumerable: true,
  52250. configurable: true
  52251. });
  52252. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52253. get: function () {
  52254. return ActionManager._OnCenterPickTrigger;
  52255. },
  52256. enumerable: true,
  52257. configurable: true
  52258. });
  52259. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52260. get: function () {
  52261. return ActionManager._OnPickDownTrigger;
  52262. },
  52263. enumerable: true,
  52264. configurable: true
  52265. });
  52266. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52267. get: function () {
  52268. return ActionManager._OnDoublePickTrigger;
  52269. },
  52270. enumerable: true,
  52271. configurable: true
  52272. });
  52273. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52274. get: function () {
  52275. return ActionManager._OnPickUpTrigger;
  52276. },
  52277. enumerable: true,
  52278. configurable: true
  52279. });
  52280. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52281. /// This trigger will only be raised if you also declared a OnPickDown
  52282. get: function () {
  52283. return ActionManager._OnPickOutTrigger;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52289. get: function () {
  52290. return ActionManager._OnLongPressTrigger;
  52291. },
  52292. enumerable: true,
  52293. configurable: true
  52294. });
  52295. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52296. get: function () {
  52297. return ActionManager._OnPointerOverTrigger;
  52298. },
  52299. enumerable: true,
  52300. configurable: true
  52301. });
  52302. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52303. get: function () {
  52304. return ActionManager._OnPointerOutTrigger;
  52305. },
  52306. enumerable: true,
  52307. configurable: true
  52308. });
  52309. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52310. get: function () {
  52311. return ActionManager._OnEveryFrameTrigger;
  52312. },
  52313. enumerable: true,
  52314. configurable: true
  52315. });
  52316. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52317. get: function () {
  52318. return ActionManager._OnIntersectionEnterTrigger;
  52319. },
  52320. enumerable: true,
  52321. configurable: true
  52322. });
  52323. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52324. get: function () {
  52325. return ActionManager._OnIntersectionExitTrigger;
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52331. get: function () {
  52332. return ActionManager._OnKeyDownTrigger;
  52333. },
  52334. enumerable: true,
  52335. configurable: true
  52336. });
  52337. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52338. get: function () {
  52339. return ActionManager._OnKeyUpTrigger;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. // Methods
  52345. ActionManager.prototype.dispose = function () {
  52346. var index = this._scene._actionManagers.indexOf(this);
  52347. for (var i = 0; i < this.actions.length; i++) {
  52348. var action = this.actions[i];
  52349. ActionManager.Triggers[action.trigger]--;
  52350. if (ActionManager.Triggers[action.trigger] === 0) {
  52351. delete ActionManager.Triggers[action.trigger];
  52352. }
  52353. }
  52354. if (index > -1) {
  52355. this._scene._actionManagers.splice(index, 1);
  52356. }
  52357. };
  52358. ActionManager.prototype.getScene = function () {
  52359. return this._scene;
  52360. };
  52361. /**
  52362. * Does this action manager handles actions of any of the given triggers
  52363. * @param {number[]} triggers - the triggers to be tested
  52364. * @return {boolean} whether one (or more) of the triggers is handeled
  52365. */
  52366. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52367. for (var index = 0; index < this.actions.length; index++) {
  52368. var action = this.actions[index];
  52369. if (triggers.indexOf(action.trigger) > -1) {
  52370. return true;
  52371. }
  52372. }
  52373. return false;
  52374. };
  52375. /**
  52376. * Does this action manager handles actions of a given trigger
  52377. * @param trigger defines the trigger to be tested
  52378. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52379. * @return whether the trigger is handled
  52380. */
  52381. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52382. for (var index = 0; index < this.actions.length; index++) {
  52383. var action = this.actions[index];
  52384. if (action.trigger === trigger) {
  52385. if (parameterPredicate) {
  52386. if (parameterPredicate(action.getTriggerParameter())) {
  52387. return true;
  52388. }
  52389. }
  52390. else {
  52391. return true;
  52392. }
  52393. }
  52394. }
  52395. return false;
  52396. };
  52397. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52398. /**
  52399. * Does this action manager has pointer triggers
  52400. * @return {boolean} whether or not it has pointer triggers
  52401. */
  52402. get: function () {
  52403. for (var index = 0; index < this.actions.length; index++) {
  52404. var action = this.actions[index];
  52405. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52406. return true;
  52407. }
  52408. }
  52409. return false;
  52410. },
  52411. enumerable: true,
  52412. configurable: true
  52413. });
  52414. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52415. /**
  52416. * Does this action manager has pick triggers
  52417. * @return {boolean} whether or not it has pick triggers
  52418. */
  52419. get: function () {
  52420. for (var index = 0; index < this.actions.length; index++) {
  52421. var action = this.actions[index];
  52422. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52423. return true;
  52424. }
  52425. }
  52426. return false;
  52427. },
  52428. enumerable: true,
  52429. configurable: true
  52430. });
  52431. Object.defineProperty(ActionManager, "HasTriggers", {
  52432. /**
  52433. * Does exist one action manager with at least one trigger
  52434. * @return {boolean} whether or not it exists one action manager with one trigger
  52435. **/
  52436. get: function () {
  52437. for (var t in ActionManager.Triggers) {
  52438. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52439. return true;
  52440. }
  52441. }
  52442. return false;
  52443. },
  52444. enumerable: true,
  52445. configurable: true
  52446. });
  52447. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52448. /**
  52449. * Does exist one action manager with at least one pick trigger
  52450. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52451. **/
  52452. get: function () {
  52453. for (var t in ActionManager.Triggers) {
  52454. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52455. var t_int = parseInt(t);
  52456. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52457. return true;
  52458. }
  52459. }
  52460. }
  52461. return false;
  52462. },
  52463. enumerable: true,
  52464. configurable: true
  52465. });
  52466. /**
  52467. * Does exist one action manager that handles actions of a given trigger
  52468. * @param {number} trigger - the trigger to be tested
  52469. * @return {boolean} whether the trigger is handeled by at least one action manager
  52470. **/
  52471. ActionManager.HasSpecificTrigger = function (trigger) {
  52472. for (var t in ActionManager.Triggers) {
  52473. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52474. var t_int = parseInt(t);
  52475. if (t_int === trigger) {
  52476. return true;
  52477. }
  52478. }
  52479. }
  52480. return false;
  52481. };
  52482. /**
  52483. * Registers an action to this action manager
  52484. * @param {BABYLON.Action} action - the action to be registered
  52485. * @return {BABYLON.Action} the action amended (prepared) after registration
  52486. */
  52487. ActionManager.prototype.registerAction = function (action) {
  52488. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52489. if (this.getScene().actionManager !== this) {
  52490. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52491. return null;
  52492. }
  52493. }
  52494. this.actions.push(action);
  52495. if (ActionManager.Triggers[action.trigger]) {
  52496. ActionManager.Triggers[action.trigger]++;
  52497. }
  52498. else {
  52499. ActionManager.Triggers[action.trigger] = 1;
  52500. }
  52501. action._actionManager = this;
  52502. action._prepare();
  52503. return action;
  52504. };
  52505. /**
  52506. * Unregisters an action to this action manager
  52507. * @param action The action to be unregistered
  52508. * @return whether the action has been unregistered
  52509. */
  52510. ActionManager.prototype.unregisterAction = function (action) {
  52511. var index = this.actions.indexOf(action);
  52512. if (index !== -1) {
  52513. this.actions.splice(index, 1);
  52514. ActionManager.Triggers[action.trigger] -= 1;
  52515. if (ActionManager.Triggers[action.trigger] === 0) {
  52516. delete ActionManager.Triggers[action.trigger];
  52517. }
  52518. delete action._actionManager;
  52519. return true;
  52520. }
  52521. return false;
  52522. };
  52523. /**
  52524. * Process a specific trigger
  52525. * @param {number} trigger - the trigger to process
  52526. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52527. */
  52528. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52529. for (var index = 0; index < this.actions.length; index++) {
  52530. var action = this.actions[index];
  52531. if (action.trigger === trigger) {
  52532. if (evt) {
  52533. if (trigger === ActionManager.OnKeyUpTrigger
  52534. || trigger === ActionManager.OnKeyDownTrigger) {
  52535. var parameter = action.getTriggerParameter();
  52536. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52537. if (!parameter.toLowerCase) {
  52538. continue;
  52539. }
  52540. var lowerCase = parameter.toLowerCase();
  52541. if (lowerCase !== evt.sourceEvent.key) {
  52542. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52543. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52544. if (actualkey !== lowerCase) {
  52545. continue;
  52546. }
  52547. }
  52548. }
  52549. }
  52550. }
  52551. action._executeCurrent(evt);
  52552. }
  52553. }
  52554. };
  52555. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52556. var properties = propertyPath.split(".");
  52557. for (var index = 0; index < properties.length - 1; index++) {
  52558. target = target[properties[index]];
  52559. }
  52560. return target;
  52561. };
  52562. ActionManager.prototype._getProperty = function (propertyPath) {
  52563. var properties = propertyPath.split(".");
  52564. return properties[properties.length - 1];
  52565. };
  52566. ActionManager.prototype.serialize = function (name) {
  52567. var root = {
  52568. children: new Array(),
  52569. name: name,
  52570. type: 3,
  52571. properties: new Array() // Empty for root but required
  52572. };
  52573. for (var i = 0; i < this.actions.length; i++) {
  52574. var triggerObject = {
  52575. type: 0,
  52576. children: new Array(),
  52577. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52578. properties: new Array()
  52579. };
  52580. var triggerOptions = this.actions[i].triggerOptions;
  52581. if (triggerOptions && typeof triggerOptions !== "number") {
  52582. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52583. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52584. }
  52585. else {
  52586. var parameter = {};
  52587. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52588. if (triggerOptions.parameter.mesh) {
  52589. parameter._meshId = triggerOptions.parameter.mesh.id;
  52590. }
  52591. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52592. }
  52593. }
  52594. // Serialize child action, recursively
  52595. this.actions[i].serialize(triggerObject);
  52596. // Add serialized trigger
  52597. root.children.push(triggerObject);
  52598. }
  52599. return root;
  52600. };
  52601. ActionManager.Parse = function (parsedActions, object, scene) {
  52602. var actionManager = new ActionManager(scene);
  52603. if (object === null)
  52604. scene.actionManager = actionManager;
  52605. else
  52606. object.actionManager = actionManager;
  52607. // instanciate a new object
  52608. var instanciate = function (name, params) {
  52609. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52610. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52611. newInstance.constructor.apply(newInstance, params);
  52612. return newInstance;
  52613. };
  52614. var parseParameter = function (name, value, target, propertyPath) {
  52615. if (propertyPath === null) {
  52616. // String, boolean or float
  52617. var floatValue = parseFloat(value);
  52618. if (value === "true" || value === "false")
  52619. return value === "true";
  52620. else
  52621. return isNaN(floatValue) ? value : floatValue;
  52622. }
  52623. var effectiveTarget = propertyPath.split(".");
  52624. var values = value.split(",");
  52625. // Get effective Target
  52626. for (var i = 0; i < effectiveTarget.length; i++) {
  52627. target = target[effectiveTarget[i]];
  52628. }
  52629. // Return appropriate value with its type
  52630. if (typeof (target) === "boolean")
  52631. return values[0] === "true";
  52632. if (typeof (target) === "string")
  52633. return values[0];
  52634. // Parameters with multiple values such as Vector3 etc.
  52635. var split = new Array();
  52636. for (var i = 0; i < values.length; i++)
  52637. split.push(parseFloat(values[i]));
  52638. if (target instanceof BABYLON.Vector3)
  52639. return BABYLON.Vector3.FromArray(split);
  52640. if (target instanceof BABYLON.Vector4)
  52641. return BABYLON.Vector4.FromArray(split);
  52642. if (target instanceof BABYLON.Color3)
  52643. return BABYLON.Color3.FromArray(split);
  52644. if (target instanceof BABYLON.Color4)
  52645. return BABYLON.Color4.FromArray(split);
  52646. return parseFloat(values[0]);
  52647. };
  52648. // traverse graph per trigger
  52649. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52650. if (combineArray === void 0) { combineArray = null; }
  52651. if (parsedAction.detached)
  52652. return;
  52653. var parameters = new Array();
  52654. var target = null;
  52655. var propertyPath = null;
  52656. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52657. // Parameters
  52658. if (parsedAction.type === 2)
  52659. parameters.push(actionManager);
  52660. else
  52661. parameters.push(trigger);
  52662. if (combine) {
  52663. var actions = new Array();
  52664. for (var j = 0; j < parsedAction.combine.length; j++) {
  52665. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52666. }
  52667. parameters.push(actions);
  52668. }
  52669. else {
  52670. for (var i = 0; i < parsedAction.properties.length; i++) {
  52671. var value = parsedAction.properties[i].value;
  52672. var name = parsedAction.properties[i].name;
  52673. var targetType = parsedAction.properties[i].targetType;
  52674. if (name === "target")
  52675. if (targetType !== null && targetType === "SceneProperties")
  52676. value = target = scene;
  52677. else
  52678. value = target = scene.getNodeByName(value);
  52679. else if (name === "parent")
  52680. value = scene.getNodeByName(value);
  52681. else if (name === "sound")
  52682. value = scene.getSoundByName(value);
  52683. else if (name !== "propertyPath") {
  52684. if (parsedAction.type === 2 && name === "operator")
  52685. value = BABYLON.ValueCondition[value];
  52686. else
  52687. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52688. }
  52689. else {
  52690. propertyPath = value;
  52691. }
  52692. parameters.push(value);
  52693. }
  52694. }
  52695. if (combineArray === null) {
  52696. parameters.push(condition);
  52697. }
  52698. else {
  52699. parameters.push(null);
  52700. }
  52701. // If interpolate value action
  52702. if (parsedAction.name === "InterpolateValueAction") {
  52703. var param = parameters[parameters.length - 2];
  52704. parameters[parameters.length - 1] = param;
  52705. parameters[parameters.length - 2] = condition;
  52706. }
  52707. // Action or condition(s) and not CombineAction
  52708. var newAction = instanciate(parsedAction.name, parameters);
  52709. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52710. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52711. if (action)
  52712. action.then(nothing);
  52713. else
  52714. actionManager.registerAction(nothing);
  52715. action = nothing;
  52716. }
  52717. if (combineArray === null) {
  52718. if (newAction instanceof BABYLON.Condition) {
  52719. condition = newAction;
  52720. newAction = action;
  52721. }
  52722. else {
  52723. condition = null;
  52724. if (action)
  52725. action.then(newAction);
  52726. else
  52727. actionManager.registerAction(newAction);
  52728. }
  52729. }
  52730. else {
  52731. combineArray.push(newAction);
  52732. }
  52733. for (var i = 0; i < parsedAction.children.length; i++)
  52734. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52735. };
  52736. // triggers
  52737. for (var i = 0; i < parsedActions.children.length; i++) {
  52738. var triggerParams;
  52739. var trigger = parsedActions.children[i];
  52740. if (trigger.properties.length > 0) {
  52741. var param = trigger.properties[0].value;
  52742. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52743. if (value._meshId) {
  52744. value.mesh = scene.getMeshByID(value._meshId);
  52745. }
  52746. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52747. }
  52748. else
  52749. triggerParams = ActionManager[trigger.name];
  52750. for (var j = 0; j < trigger.children.length; j++) {
  52751. if (!trigger.detached)
  52752. traverse(trigger.children[j], triggerParams, null, null);
  52753. }
  52754. }
  52755. };
  52756. ActionManager.GetTriggerName = function (trigger) {
  52757. switch (trigger) {
  52758. case 0: return "NothingTrigger";
  52759. case 1: return "OnPickTrigger";
  52760. case 2: return "OnLeftPickTrigger";
  52761. case 3: return "OnRightPickTrigger";
  52762. case 4: return "OnCenterPickTrigger";
  52763. case 5: return "OnPickDownTrigger";
  52764. case 6: return "OnPickUpTrigger";
  52765. case 7: return "OnLongPressTrigger";
  52766. case 8: return "OnPointerOverTrigger";
  52767. case 9: return "OnPointerOutTrigger";
  52768. case 10: return "OnEveryFrameTrigger";
  52769. case 11: return "OnIntersectionEnterTrigger";
  52770. case 12: return "OnIntersectionExitTrigger";
  52771. case 13: return "OnKeyDownTrigger";
  52772. case 14: return "OnKeyUpTrigger";
  52773. case 15: return "OnPickOutTrigger";
  52774. default: return "";
  52775. }
  52776. };
  52777. // Statics
  52778. ActionManager._NothingTrigger = 0;
  52779. ActionManager._OnPickTrigger = 1;
  52780. ActionManager._OnLeftPickTrigger = 2;
  52781. ActionManager._OnRightPickTrigger = 3;
  52782. ActionManager._OnCenterPickTrigger = 4;
  52783. ActionManager._OnPickDownTrigger = 5;
  52784. ActionManager._OnDoublePickTrigger = 6;
  52785. ActionManager._OnPickUpTrigger = 7;
  52786. ActionManager._OnLongPressTrigger = 8;
  52787. ActionManager._OnPointerOverTrigger = 9;
  52788. ActionManager._OnPointerOutTrigger = 10;
  52789. ActionManager._OnEveryFrameTrigger = 11;
  52790. ActionManager._OnIntersectionEnterTrigger = 12;
  52791. ActionManager._OnIntersectionExitTrigger = 13;
  52792. ActionManager._OnKeyDownTrigger = 14;
  52793. ActionManager._OnKeyUpTrigger = 15;
  52794. ActionManager._OnPickOutTrigger = 16;
  52795. ActionManager.Triggers = {};
  52796. return ActionManager;
  52797. }());
  52798. BABYLON.ActionManager = ActionManager;
  52799. })(BABYLON || (BABYLON = {}));
  52800. //# sourceMappingURL=babylon.actionManager.js.map
  52801. var BABYLON;
  52802. (function (BABYLON) {
  52803. var InterpolateValueAction = /** @class */ (function (_super) {
  52804. __extends(InterpolateValueAction, _super);
  52805. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52806. if (duration === void 0) { duration = 1000; }
  52807. var _this = _super.call(this, triggerOptions, condition) || this;
  52808. _this.propertyPath = propertyPath;
  52809. _this.value = value;
  52810. _this.duration = duration;
  52811. _this.stopOtherAnimations = stopOtherAnimations;
  52812. _this.onInterpolationDone = onInterpolationDone;
  52813. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52814. _this._target = _this._effectiveTarget = target;
  52815. return _this;
  52816. }
  52817. InterpolateValueAction.prototype._prepare = function () {
  52818. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52819. this._property = this._getProperty(this.propertyPath);
  52820. };
  52821. InterpolateValueAction.prototype.execute = function () {
  52822. var _this = this;
  52823. var scene = this._actionManager.getScene();
  52824. var keys = [
  52825. {
  52826. frame: 0,
  52827. value: this._effectiveTarget[this._property]
  52828. }, {
  52829. frame: 100,
  52830. value: this.value
  52831. }
  52832. ];
  52833. var dataType;
  52834. if (typeof this.value === "number") {
  52835. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52836. }
  52837. else if (this.value instanceof BABYLON.Color3) {
  52838. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52839. }
  52840. else if (this.value instanceof BABYLON.Vector3) {
  52841. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52842. }
  52843. else if (this.value instanceof BABYLON.Matrix) {
  52844. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52845. }
  52846. else if (this.value instanceof BABYLON.Quaternion) {
  52847. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52848. }
  52849. else {
  52850. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52851. return;
  52852. }
  52853. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52854. animation.setKeys(keys);
  52855. if (this.stopOtherAnimations) {
  52856. scene.stopAnimation(this._effectiveTarget);
  52857. }
  52858. var wrapper = function () {
  52859. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52860. if (_this.onInterpolationDone) {
  52861. _this.onInterpolationDone();
  52862. }
  52863. };
  52864. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52865. };
  52866. InterpolateValueAction.prototype.serialize = function (parent) {
  52867. return _super.prototype._serialize.call(this, {
  52868. name: "InterpolateValueAction",
  52869. properties: [
  52870. BABYLON.Action._GetTargetProperty(this._target),
  52871. { name: "propertyPath", value: this.propertyPath },
  52872. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52873. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52874. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52875. ]
  52876. }, parent);
  52877. };
  52878. return InterpolateValueAction;
  52879. }(BABYLON.Action));
  52880. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52881. })(BABYLON || (BABYLON = {}));
  52882. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. var SwitchBooleanAction = /** @class */ (function (_super) {
  52886. __extends(SwitchBooleanAction, _super);
  52887. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52888. var _this = _super.call(this, triggerOptions, condition) || this;
  52889. _this.propertyPath = propertyPath;
  52890. _this._target = _this._effectiveTarget = target;
  52891. return _this;
  52892. }
  52893. SwitchBooleanAction.prototype._prepare = function () {
  52894. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52895. this._property = this._getProperty(this.propertyPath);
  52896. };
  52897. SwitchBooleanAction.prototype.execute = function () {
  52898. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52899. };
  52900. SwitchBooleanAction.prototype.serialize = function (parent) {
  52901. return _super.prototype._serialize.call(this, {
  52902. name: "SwitchBooleanAction",
  52903. properties: [
  52904. BABYLON.Action._GetTargetProperty(this._target),
  52905. { name: "propertyPath", value: this.propertyPath }
  52906. ]
  52907. }, parent);
  52908. };
  52909. return SwitchBooleanAction;
  52910. }(BABYLON.Action));
  52911. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52912. var SetStateAction = /** @class */ (function (_super) {
  52913. __extends(SetStateAction, _super);
  52914. function SetStateAction(triggerOptions, target, value, condition) {
  52915. var _this = _super.call(this, triggerOptions, condition) || this;
  52916. _this.value = value;
  52917. _this._target = target;
  52918. return _this;
  52919. }
  52920. SetStateAction.prototype.execute = function () {
  52921. this._target.state = this.value;
  52922. };
  52923. SetStateAction.prototype.serialize = function (parent) {
  52924. return _super.prototype._serialize.call(this, {
  52925. name: "SetStateAction",
  52926. properties: [
  52927. BABYLON.Action._GetTargetProperty(this._target),
  52928. { name: "value", value: this.value }
  52929. ]
  52930. }, parent);
  52931. };
  52932. return SetStateAction;
  52933. }(BABYLON.Action));
  52934. BABYLON.SetStateAction = SetStateAction;
  52935. var SetValueAction = /** @class */ (function (_super) {
  52936. __extends(SetValueAction, _super);
  52937. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52938. var _this = _super.call(this, triggerOptions, condition) || this;
  52939. _this.propertyPath = propertyPath;
  52940. _this.value = value;
  52941. _this._target = _this._effectiveTarget = target;
  52942. return _this;
  52943. }
  52944. SetValueAction.prototype._prepare = function () {
  52945. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52946. this._property = this._getProperty(this.propertyPath);
  52947. };
  52948. SetValueAction.prototype.execute = function () {
  52949. this._effectiveTarget[this._property] = this.value;
  52950. if (this._target.markAsDirty) {
  52951. this._target.markAsDirty(this._property);
  52952. }
  52953. };
  52954. SetValueAction.prototype.serialize = function (parent) {
  52955. return _super.prototype._serialize.call(this, {
  52956. name: "SetValueAction",
  52957. properties: [
  52958. BABYLON.Action._GetTargetProperty(this._target),
  52959. { name: "propertyPath", value: this.propertyPath },
  52960. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52961. ]
  52962. }, parent);
  52963. };
  52964. return SetValueAction;
  52965. }(BABYLON.Action));
  52966. BABYLON.SetValueAction = SetValueAction;
  52967. var IncrementValueAction = /** @class */ (function (_super) {
  52968. __extends(IncrementValueAction, _super);
  52969. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52970. var _this = _super.call(this, triggerOptions, condition) || this;
  52971. _this.propertyPath = propertyPath;
  52972. _this.value = value;
  52973. _this._target = _this._effectiveTarget = target;
  52974. return _this;
  52975. }
  52976. IncrementValueAction.prototype._prepare = function () {
  52977. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52978. this._property = this._getProperty(this.propertyPath);
  52979. if (typeof this._effectiveTarget[this._property] !== "number") {
  52980. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52981. }
  52982. };
  52983. IncrementValueAction.prototype.execute = function () {
  52984. this._effectiveTarget[this._property] += this.value;
  52985. if (this._target.markAsDirty) {
  52986. this._target.markAsDirty(this._property);
  52987. }
  52988. };
  52989. IncrementValueAction.prototype.serialize = function (parent) {
  52990. return _super.prototype._serialize.call(this, {
  52991. name: "IncrementValueAction",
  52992. properties: [
  52993. BABYLON.Action._GetTargetProperty(this._target),
  52994. { name: "propertyPath", value: this.propertyPath },
  52995. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52996. ]
  52997. }, parent);
  52998. };
  52999. return IncrementValueAction;
  53000. }(BABYLON.Action));
  53001. BABYLON.IncrementValueAction = IncrementValueAction;
  53002. var PlayAnimationAction = /** @class */ (function (_super) {
  53003. __extends(PlayAnimationAction, _super);
  53004. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53005. var _this = _super.call(this, triggerOptions, condition) || this;
  53006. _this.from = from;
  53007. _this.to = to;
  53008. _this.loop = loop;
  53009. _this._target = target;
  53010. return _this;
  53011. }
  53012. PlayAnimationAction.prototype._prepare = function () {
  53013. };
  53014. PlayAnimationAction.prototype.execute = function () {
  53015. var scene = this._actionManager.getScene();
  53016. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53017. };
  53018. PlayAnimationAction.prototype.serialize = function (parent) {
  53019. return _super.prototype._serialize.call(this, {
  53020. name: "PlayAnimationAction",
  53021. properties: [
  53022. BABYLON.Action._GetTargetProperty(this._target),
  53023. { name: "from", value: String(this.from) },
  53024. { name: "to", value: String(this.to) },
  53025. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53026. ]
  53027. }, parent);
  53028. };
  53029. return PlayAnimationAction;
  53030. }(BABYLON.Action));
  53031. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53032. var StopAnimationAction = /** @class */ (function (_super) {
  53033. __extends(StopAnimationAction, _super);
  53034. function StopAnimationAction(triggerOptions, target, condition) {
  53035. var _this = _super.call(this, triggerOptions, condition) || this;
  53036. _this._target = target;
  53037. return _this;
  53038. }
  53039. StopAnimationAction.prototype._prepare = function () {
  53040. };
  53041. StopAnimationAction.prototype.execute = function () {
  53042. var scene = this._actionManager.getScene();
  53043. scene.stopAnimation(this._target);
  53044. };
  53045. StopAnimationAction.prototype.serialize = function (parent) {
  53046. return _super.prototype._serialize.call(this, {
  53047. name: "StopAnimationAction",
  53048. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53049. }, parent);
  53050. };
  53051. return StopAnimationAction;
  53052. }(BABYLON.Action));
  53053. BABYLON.StopAnimationAction = StopAnimationAction;
  53054. var DoNothingAction = /** @class */ (function (_super) {
  53055. __extends(DoNothingAction, _super);
  53056. function DoNothingAction(triggerOptions, condition) {
  53057. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53058. return _super.call(this, triggerOptions, condition) || this;
  53059. }
  53060. DoNothingAction.prototype.execute = function () {
  53061. };
  53062. DoNothingAction.prototype.serialize = function (parent) {
  53063. return _super.prototype._serialize.call(this, {
  53064. name: "DoNothingAction",
  53065. properties: []
  53066. }, parent);
  53067. };
  53068. return DoNothingAction;
  53069. }(BABYLON.Action));
  53070. BABYLON.DoNothingAction = DoNothingAction;
  53071. var CombineAction = /** @class */ (function (_super) {
  53072. __extends(CombineAction, _super);
  53073. function CombineAction(triggerOptions, children, condition) {
  53074. var _this = _super.call(this, triggerOptions, condition) || this;
  53075. _this.children = children;
  53076. return _this;
  53077. }
  53078. CombineAction.prototype._prepare = function () {
  53079. for (var index = 0; index < this.children.length; index++) {
  53080. this.children[index]._actionManager = this._actionManager;
  53081. this.children[index]._prepare();
  53082. }
  53083. };
  53084. CombineAction.prototype.execute = function (evt) {
  53085. for (var index = 0; index < this.children.length; index++) {
  53086. this.children[index].execute(evt);
  53087. }
  53088. };
  53089. CombineAction.prototype.serialize = function (parent) {
  53090. var serializationObject = _super.prototype._serialize.call(this, {
  53091. name: "CombineAction",
  53092. properties: [],
  53093. combine: []
  53094. }, parent);
  53095. for (var i = 0; i < this.children.length; i++) {
  53096. serializationObject.combine.push(this.children[i].serialize(null));
  53097. }
  53098. return serializationObject;
  53099. };
  53100. return CombineAction;
  53101. }(BABYLON.Action));
  53102. BABYLON.CombineAction = CombineAction;
  53103. var ExecuteCodeAction = /** @class */ (function (_super) {
  53104. __extends(ExecuteCodeAction, _super);
  53105. function ExecuteCodeAction(triggerOptions, func, condition) {
  53106. var _this = _super.call(this, triggerOptions, condition) || this;
  53107. _this.func = func;
  53108. return _this;
  53109. }
  53110. ExecuteCodeAction.prototype.execute = function (evt) {
  53111. this.func(evt);
  53112. };
  53113. return ExecuteCodeAction;
  53114. }(BABYLON.Action));
  53115. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53116. var SetParentAction = /** @class */ (function (_super) {
  53117. __extends(SetParentAction, _super);
  53118. function SetParentAction(triggerOptions, target, parent, condition) {
  53119. var _this = _super.call(this, triggerOptions, condition) || this;
  53120. _this._target = target;
  53121. _this._parent = parent;
  53122. return _this;
  53123. }
  53124. SetParentAction.prototype._prepare = function () {
  53125. };
  53126. SetParentAction.prototype.execute = function () {
  53127. if (this._target.parent === this._parent) {
  53128. return;
  53129. }
  53130. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53131. invertParentWorldMatrix.invert();
  53132. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53133. this._target.parent = this._parent;
  53134. };
  53135. SetParentAction.prototype.serialize = function (parent) {
  53136. return _super.prototype._serialize.call(this, {
  53137. name: "SetParentAction",
  53138. properties: [
  53139. BABYLON.Action._GetTargetProperty(this._target),
  53140. BABYLON.Action._GetTargetProperty(this._parent),
  53141. ]
  53142. }, parent);
  53143. };
  53144. return SetParentAction;
  53145. }(BABYLON.Action));
  53146. BABYLON.SetParentAction = SetParentAction;
  53147. var PlaySoundAction = /** @class */ (function (_super) {
  53148. __extends(PlaySoundAction, _super);
  53149. function PlaySoundAction(triggerOptions, sound, condition) {
  53150. var _this = _super.call(this, triggerOptions, condition) || this;
  53151. _this._sound = sound;
  53152. return _this;
  53153. }
  53154. PlaySoundAction.prototype._prepare = function () {
  53155. };
  53156. PlaySoundAction.prototype.execute = function () {
  53157. if (this._sound !== undefined)
  53158. this._sound.play();
  53159. };
  53160. PlaySoundAction.prototype.serialize = function (parent) {
  53161. return _super.prototype._serialize.call(this, {
  53162. name: "PlaySoundAction",
  53163. properties: [{ name: "sound", value: this._sound.name }]
  53164. }, parent);
  53165. };
  53166. return PlaySoundAction;
  53167. }(BABYLON.Action));
  53168. BABYLON.PlaySoundAction = PlaySoundAction;
  53169. var StopSoundAction = /** @class */ (function (_super) {
  53170. __extends(StopSoundAction, _super);
  53171. function StopSoundAction(triggerOptions, sound, condition) {
  53172. var _this = _super.call(this, triggerOptions, condition) || this;
  53173. _this._sound = sound;
  53174. return _this;
  53175. }
  53176. StopSoundAction.prototype._prepare = function () {
  53177. };
  53178. StopSoundAction.prototype.execute = function () {
  53179. if (this._sound !== undefined)
  53180. this._sound.stop();
  53181. };
  53182. StopSoundAction.prototype.serialize = function (parent) {
  53183. return _super.prototype._serialize.call(this, {
  53184. name: "StopSoundAction",
  53185. properties: [{ name: "sound", value: this._sound.name }]
  53186. }, parent);
  53187. };
  53188. return StopSoundAction;
  53189. }(BABYLON.Action));
  53190. BABYLON.StopSoundAction = StopSoundAction;
  53191. })(BABYLON || (BABYLON = {}));
  53192. //# sourceMappingURL=babylon.directActions.js.map
  53193. var BABYLON;
  53194. (function (BABYLON) {
  53195. var SpriteManager = /** @class */ (function () {
  53196. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53197. if (epsilon === void 0) { epsilon = 0.01; }
  53198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53199. this.name = name;
  53200. this.sprites = new Array();
  53201. this.renderingGroupId = 0;
  53202. this.layerMask = 0x0FFFFFFF;
  53203. this.fogEnabled = true;
  53204. this.isPickable = false;
  53205. /**
  53206. * An event triggered when the manager is disposed.
  53207. */
  53208. this.onDisposeObservable = new BABYLON.Observable();
  53209. this._vertexBuffers = {};
  53210. this._capacity = capacity;
  53211. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53212. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53213. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53214. if (cellSize.width && cellSize.height) {
  53215. this.cellWidth = cellSize.width;
  53216. this.cellHeight = cellSize.height;
  53217. }
  53218. else if (cellSize !== undefined) {
  53219. this.cellWidth = cellSize;
  53220. this.cellHeight = cellSize;
  53221. }
  53222. else {
  53223. return;
  53224. }
  53225. this._epsilon = epsilon;
  53226. this._scene = scene;
  53227. this._scene.spriteManagers.push(this);
  53228. var indices = [];
  53229. var index = 0;
  53230. for (var count = 0; count < capacity; count++) {
  53231. indices.push(index);
  53232. indices.push(index + 1);
  53233. indices.push(index + 2);
  53234. indices.push(index);
  53235. indices.push(index + 2);
  53236. indices.push(index + 3);
  53237. index += 4;
  53238. }
  53239. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53240. // VBO
  53241. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53242. this._vertexData = new Float32Array(capacity * 16 * 4);
  53243. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53244. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53245. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53246. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53247. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53248. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53249. this._vertexBuffers["options"] = options;
  53250. this._vertexBuffers["cellInfo"] = cellInfo;
  53251. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53252. // Effects
  53253. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53254. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53255. }
  53256. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53257. set: function (callback) {
  53258. if (this._onDisposeObserver) {
  53259. this.onDisposeObservable.remove(this._onDisposeObserver);
  53260. }
  53261. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(SpriteManager.prototype, "texture", {
  53267. get: function () {
  53268. return this._spriteTexture;
  53269. },
  53270. set: function (value) {
  53271. this._spriteTexture = value;
  53272. },
  53273. enumerable: true,
  53274. configurable: true
  53275. });
  53276. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53277. var arrayOffset = index * 16;
  53278. if (offsetX === 0)
  53279. offsetX = this._epsilon;
  53280. else if (offsetX === 1)
  53281. offsetX = 1 - this._epsilon;
  53282. if (offsetY === 0)
  53283. offsetY = this._epsilon;
  53284. else if (offsetY === 1)
  53285. offsetY = 1 - this._epsilon;
  53286. this._vertexData[arrayOffset] = sprite.position.x;
  53287. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53288. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53289. this._vertexData[arrayOffset + 3] = sprite.angle;
  53290. this._vertexData[arrayOffset + 4] = sprite.width;
  53291. this._vertexData[arrayOffset + 5] = sprite.height;
  53292. this._vertexData[arrayOffset + 6] = offsetX;
  53293. this._vertexData[arrayOffset + 7] = offsetY;
  53294. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53295. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53296. var offset = (sprite.cellIndex / rowSize) >> 0;
  53297. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53298. this._vertexData[arrayOffset + 11] = offset;
  53299. // Color
  53300. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53301. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53302. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53303. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53304. };
  53305. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53306. var count = Math.min(this._capacity, this.sprites.length);
  53307. var min = BABYLON.Vector3.Zero();
  53308. var max = BABYLON.Vector3.Zero();
  53309. var distance = Number.MAX_VALUE;
  53310. var currentSprite = null;
  53311. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53312. var cameraView = camera.getViewMatrix();
  53313. for (var index = 0; index < count; index++) {
  53314. var sprite = this.sprites[index];
  53315. if (!sprite) {
  53316. continue;
  53317. }
  53318. if (predicate) {
  53319. if (!predicate(sprite)) {
  53320. continue;
  53321. }
  53322. }
  53323. else if (!sprite.isPickable) {
  53324. continue;
  53325. }
  53326. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53327. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53328. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53329. if (ray.intersectsBoxMinMax(min, max)) {
  53330. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53331. if (distance > currentDistance) {
  53332. distance = currentDistance;
  53333. currentSprite = sprite;
  53334. if (fastCheck) {
  53335. break;
  53336. }
  53337. }
  53338. }
  53339. }
  53340. if (currentSprite) {
  53341. var result = new BABYLON.PickingInfo();
  53342. result.hit = true;
  53343. result.pickedSprite = currentSprite;
  53344. result.distance = distance;
  53345. return result;
  53346. }
  53347. return null;
  53348. };
  53349. SpriteManager.prototype.render = function () {
  53350. // Check
  53351. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53352. return;
  53353. var engine = this._scene.getEngine();
  53354. var baseSize = this._spriteTexture.getBaseSize();
  53355. // Sprites
  53356. var deltaTime = engine.getDeltaTime();
  53357. var max = Math.min(this._capacity, this.sprites.length);
  53358. var rowSize = baseSize.width / this.cellWidth;
  53359. var offset = 0;
  53360. for (var index = 0; index < max; index++) {
  53361. var sprite = this.sprites[index];
  53362. if (!sprite) {
  53363. continue;
  53364. }
  53365. sprite._animate(deltaTime);
  53366. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53367. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53368. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53369. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53370. }
  53371. this._buffer.update(this._vertexData);
  53372. // Render
  53373. var effect = this._effectBase;
  53374. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53375. effect = this._effectFog;
  53376. }
  53377. engine.enableEffect(effect);
  53378. var viewMatrix = this._scene.getViewMatrix();
  53379. effect.setTexture("diffuseSampler", this._spriteTexture);
  53380. effect.setMatrix("view", viewMatrix);
  53381. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53382. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53383. // Fog
  53384. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53385. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53386. effect.setColor3("vFogColor", this._scene.fogColor);
  53387. }
  53388. // VBOs
  53389. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53390. // Draw order
  53391. engine.setDepthFunctionToLessOrEqual();
  53392. effect.setBool("alphaTest", true);
  53393. engine.setColorWrite(false);
  53394. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53395. engine.setColorWrite(true);
  53396. effect.setBool("alphaTest", false);
  53397. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53398. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53400. };
  53401. SpriteManager.prototype.dispose = function () {
  53402. if (this._buffer) {
  53403. this._buffer.dispose();
  53404. this._buffer = null;
  53405. }
  53406. if (this._indexBuffer) {
  53407. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53408. this._indexBuffer = null;
  53409. }
  53410. if (this._spriteTexture) {
  53411. this._spriteTexture.dispose();
  53412. this._spriteTexture = null;
  53413. }
  53414. // Remove from scene
  53415. var index = this._scene.spriteManagers.indexOf(this);
  53416. this._scene.spriteManagers.splice(index, 1);
  53417. // Callback
  53418. this.onDisposeObservable.notifyObservers(this);
  53419. this.onDisposeObservable.clear();
  53420. };
  53421. return SpriteManager;
  53422. }());
  53423. BABYLON.SpriteManager = SpriteManager;
  53424. })(BABYLON || (BABYLON = {}));
  53425. //# sourceMappingURL=babylon.spriteManager.js.map
  53426. var BABYLON;
  53427. (function (BABYLON) {
  53428. var Sprite = /** @class */ (function () {
  53429. function Sprite(name, manager) {
  53430. this.name = name;
  53431. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53432. this.width = 1.0;
  53433. this.height = 1.0;
  53434. this.angle = 0;
  53435. this.cellIndex = 0;
  53436. this.invertU = 0;
  53437. this.invertV = 0;
  53438. this.animations = new Array();
  53439. this.isPickable = false;
  53440. this._animationStarted = false;
  53441. this._loopAnimation = false;
  53442. this._fromIndex = 0;
  53443. this._toIndex = 0;
  53444. this._delay = 0;
  53445. this._direction = 1;
  53446. this._time = 0;
  53447. this._manager = manager;
  53448. this._manager.sprites.push(this);
  53449. this.position = BABYLON.Vector3.Zero();
  53450. }
  53451. Object.defineProperty(Sprite.prototype, "size", {
  53452. get: function () {
  53453. return this.width;
  53454. },
  53455. set: function (value) {
  53456. this.width = value;
  53457. this.height = value;
  53458. },
  53459. enumerable: true,
  53460. configurable: true
  53461. });
  53462. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53463. this._fromIndex = from;
  53464. this._toIndex = to;
  53465. this._loopAnimation = loop;
  53466. this._delay = delay;
  53467. this._animationStarted = true;
  53468. this._direction = from < to ? 1 : -1;
  53469. this.cellIndex = from;
  53470. this._time = 0;
  53471. this._onAnimationEnd = onAnimationEnd;
  53472. };
  53473. Sprite.prototype.stopAnimation = function () {
  53474. this._animationStarted = false;
  53475. };
  53476. Sprite.prototype._animate = function (deltaTime) {
  53477. if (!this._animationStarted)
  53478. return;
  53479. this._time += deltaTime;
  53480. if (this._time > this._delay) {
  53481. this._time = this._time % this._delay;
  53482. this.cellIndex += this._direction;
  53483. if (this.cellIndex > this._toIndex) {
  53484. if (this._loopAnimation) {
  53485. this.cellIndex = this._fromIndex;
  53486. }
  53487. else {
  53488. this.cellIndex = this._toIndex;
  53489. this._animationStarted = false;
  53490. if (this._onAnimationEnd) {
  53491. this._onAnimationEnd();
  53492. }
  53493. if (this.disposeWhenFinishedAnimating) {
  53494. this.dispose();
  53495. }
  53496. }
  53497. }
  53498. }
  53499. };
  53500. Sprite.prototype.dispose = function () {
  53501. for (var i = 0; i < this._manager.sprites.length; i++) {
  53502. if (this._manager.sprites[i] == this) {
  53503. this._manager.sprites.splice(i, 1);
  53504. }
  53505. }
  53506. };
  53507. return Sprite;
  53508. }());
  53509. BABYLON.Sprite = Sprite;
  53510. })(BABYLON || (BABYLON = {}));
  53511. //# sourceMappingURL=babylon.sprite.js.map
  53512. var BABYLON;
  53513. (function (BABYLON) {
  53514. var IntersectionInfo = /** @class */ (function () {
  53515. function IntersectionInfo(bu, bv, distance) {
  53516. this.bu = bu;
  53517. this.bv = bv;
  53518. this.distance = distance;
  53519. this.faceId = 0;
  53520. this.subMeshId = 0;
  53521. }
  53522. return IntersectionInfo;
  53523. }());
  53524. BABYLON.IntersectionInfo = IntersectionInfo;
  53525. var PickingInfo = /** @class */ (function () {
  53526. function PickingInfo() {
  53527. this.hit = false;
  53528. this.distance = 0;
  53529. this.pickedPoint = null;
  53530. this.pickedMesh = null;
  53531. this.bu = 0;
  53532. this.bv = 0;
  53533. this.faceId = -1;
  53534. this.subMeshId = 0;
  53535. this.pickedSprite = null;
  53536. }
  53537. // Methods
  53538. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53539. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53540. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53541. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53542. return null;
  53543. }
  53544. var indices = this.pickedMesh.getIndices();
  53545. if (!indices) {
  53546. return null;
  53547. }
  53548. var result;
  53549. if (useVerticesNormals) {
  53550. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53551. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53552. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53553. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53554. normal0 = normal0.scale(this.bu);
  53555. normal1 = normal1.scale(this.bv);
  53556. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53557. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53558. }
  53559. else {
  53560. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53561. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53562. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53563. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53564. var p1p2 = vertex1.subtract(vertex2);
  53565. var p3p2 = vertex3.subtract(vertex2);
  53566. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53567. }
  53568. if (useWorldCoordinates) {
  53569. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53570. }
  53571. return BABYLON.Vector3.Normalize(result);
  53572. };
  53573. PickingInfo.prototype.getTextureCoordinates = function () {
  53574. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53575. return null;
  53576. }
  53577. var indices = this.pickedMesh.getIndices();
  53578. if (!indices) {
  53579. return null;
  53580. }
  53581. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53582. if (!uvs) {
  53583. return null;
  53584. }
  53585. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53586. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53587. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53588. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53589. uv1 = uv1.scale(this.bu);
  53590. uv2 = uv2.scale(this.bv);
  53591. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53592. };
  53593. return PickingInfo;
  53594. }());
  53595. BABYLON.PickingInfo = PickingInfo;
  53596. })(BABYLON || (BABYLON = {}));
  53597. //# sourceMappingURL=babylon.pickingInfo.js.map
  53598. var BABYLON;
  53599. (function (BABYLON) {
  53600. var Ray = /** @class */ (function () {
  53601. function Ray(origin, direction, length) {
  53602. if (length === void 0) { length = Number.MAX_VALUE; }
  53603. this.origin = origin;
  53604. this.direction = direction;
  53605. this.length = length;
  53606. }
  53607. // Methods
  53608. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53609. var d = 0.0;
  53610. var maxValue = Number.MAX_VALUE;
  53611. var inv;
  53612. var min;
  53613. var max;
  53614. var temp;
  53615. if (Math.abs(this.direction.x) < 0.0000001) {
  53616. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53617. return false;
  53618. }
  53619. }
  53620. else {
  53621. inv = 1.0 / this.direction.x;
  53622. min = (minimum.x - this.origin.x) * inv;
  53623. max = (maximum.x - this.origin.x) * inv;
  53624. if (max === -Infinity) {
  53625. max = Infinity;
  53626. }
  53627. if (min > max) {
  53628. temp = min;
  53629. min = max;
  53630. max = temp;
  53631. }
  53632. d = Math.max(min, d);
  53633. maxValue = Math.min(max, maxValue);
  53634. if (d > maxValue) {
  53635. return false;
  53636. }
  53637. }
  53638. if (Math.abs(this.direction.y) < 0.0000001) {
  53639. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53640. return false;
  53641. }
  53642. }
  53643. else {
  53644. inv = 1.0 / this.direction.y;
  53645. min = (minimum.y - this.origin.y) * inv;
  53646. max = (maximum.y - this.origin.y) * inv;
  53647. if (max === -Infinity) {
  53648. max = Infinity;
  53649. }
  53650. if (min > max) {
  53651. temp = min;
  53652. min = max;
  53653. max = temp;
  53654. }
  53655. d = Math.max(min, d);
  53656. maxValue = Math.min(max, maxValue);
  53657. if (d > maxValue) {
  53658. return false;
  53659. }
  53660. }
  53661. if (Math.abs(this.direction.z) < 0.0000001) {
  53662. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53663. return false;
  53664. }
  53665. }
  53666. else {
  53667. inv = 1.0 / this.direction.z;
  53668. min = (minimum.z - this.origin.z) * inv;
  53669. max = (maximum.z - this.origin.z) * inv;
  53670. if (max === -Infinity) {
  53671. max = Infinity;
  53672. }
  53673. if (min > max) {
  53674. temp = min;
  53675. min = max;
  53676. max = temp;
  53677. }
  53678. d = Math.max(min, d);
  53679. maxValue = Math.min(max, maxValue);
  53680. if (d > maxValue) {
  53681. return false;
  53682. }
  53683. }
  53684. return true;
  53685. };
  53686. Ray.prototype.intersectsBox = function (box) {
  53687. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53688. };
  53689. Ray.prototype.intersectsSphere = function (sphere) {
  53690. var x = sphere.center.x - this.origin.x;
  53691. var y = sphere.center.y - this.origin.y;
  53692. var z = sphere.center.z - this.origin.z;
  53693. var pyth = (x * x) + (y * y) + (z * z);
  53694. var rr = sphere.radius * sphere.radius;
  53695. if (pyth <= rr) {
  53696. return true;
  53697. }
  53698. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53699. if (dot < 0.0) {
  53700. return false;
  53701. }
  53702. var temp = pyth - (dot * dot);
  53703. return temp <= rr;
  53704. };
  53705. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53706. if (!this._edge1) {
  53707. this._edge1 = BABYLON.Vector3.Zero();
  53708. this._edge2 = BABYLON.Vector3.Zero();
  53709. this._pvec = BABYLON.Vector3.Zero();
  53710. this._tvec = BABYLON.Vector3.Zero();
  53711. this._qvec = BABYLON.Vector3.Zero();
  53712. }
  53713. vertex1.subtractToRef(vertex0, this._edge1);
  53714. vertex2.subtractToRef(vertex0, this._edge2);
  53715. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53716. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53717. if (det === 0) {
  53718. return null;
  53719. }
  53720. var invdet = 1 / det;
  53721. this.origin.subtractToRef(vertex0, this._tvec);
  53722. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53723. if (bu < 0 || bu > 1.0) {
  53724. return null;
  53725. }
  53726. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53727. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53728. if (bv < 0 || bu + bv > 1.0) {
  53729. return null;
  53730. }
  53731. //check if the distance is longer than the predefined length.
  53732. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53733. if (distance > this.length) {
  53734. return null;
  53735. }
  53736. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53737. };
  53738. Ray.prototype.intersectsPlane = function (plane) {
  53739. var distance;
  53740. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53741. if (Math.abs(result1) < 9.99999997475243E-07) {
  53742. return null;
  53743. }
  53744. else {
  53745. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53746. distance = (-plane.d - result2) / result1;
  53747. if (distance < 0.0) {
  53748. if (distance < -9.99999997475243E-07) {
  53749. return null;
  53750. }
  53751. else {
  53752. return 0;
  53753. }
  53754. }
  53755. return distance;
  53756. }
  53757. };
  53758. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53759. var tm = BABYLON.Tmp.Matrix[0];
  53760. mesh.getWorldMatrix().invertToRef(tm);
  53761. if (this._tmpRay) {
  53762. Ray.TransformToRef(this, tm, this._tmpRay);
  53763. }
  53764. else {
  53765. this._tmpRay = Ray.Transform(this, tm);
  53766. }
  53767. return mesh.intersects(this._tmpRay, fastCheck);
  53768. };
  53769. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53770. if (results) {
  53771. results.length = 0;
  53772. }
  53773. else {
  53774. results = [];
  53775. }
  53776. for (var i = 0; i < meshes.length; i++) {
  53777. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53778. if (pickInfo.hit) {
  53779. results.push(pickInfo);
  53780. }
  53781. }
  53782. results.sort(this._comparePickingInfo);
  53783. return results;
  53784. };
  53785. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53786. if (pickingInfoA.distance < pickingInfoB.distance) {
  53787. return -1;
  53788. }
  53789. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53790. return 1;
  53791. }
  53792. else {
  53793. return 0;
  53794. }
  53795. };
  53796. /**
  53797. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53798. * @param sega the first point of the segment to test the intersection against
  53799. * @param segb the second point of the segment to test the intersection against
  53800. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53801. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53802. */
  53803. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53804. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53805. var u = segb.subtract(sega);
  53806. var v = rsegb.subtract(this.origin);
  53807. var w = sega.subtract(this.origin);
  53808. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53809. var b = BABYLON.Vector3.Dot(u, v);
  53810. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53811. var d = BABYLON.Vector3.Dot(u, w);
  53812. var e = BABYLON.Vector3.Dot(v, w);
  53813. var D = a * c - b * b; // always >= 0
  53814. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53815. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53816. // compute the line parameters of the two closest points
  53817. if (D < Ray.smallnum) { // the lines are almost parallel
  53818. sN = 0.0; // force using point P0 on segment S1
  53819. sD = 1.0; // to prevent possible division by 0.0 later
  53820. tN = e;
  53821. tD = c;
  53822. }
  53823. else { // get the closest points on the infinite lines
  53824. sN = (b * e - c * d);
  53825. tN = (a * e - b * d);
  53826. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53827. sN = 0.0;
  53828. tN = e;
  53829. tD = c;
  53830. }
  53831. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53832. sN = sD;
  53833. tN = e + b;
  53834. tD = c;
  53835. }
  53836. }
  53837. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53838. tN = 0.0;
  53839. // recompute sc for this edge
  53840. if (-d < 0.0) {
  53841. sN = 0.0;
  53842. }
  53843. else if (-d > a)
  53844. sN = sD;
  53845. else {
  53846. sN = -d;
  53847. sD = a;
  53848. }
  53849. }
  53850. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53851. tN = tD;
  53852. // recompute sc for this edge
  53853. if ((-d + b) < 0.0) {
  53854. sN = 0;
  53855. }
  53856. else if ((-d + b) > a) {
  53857. sN = sD;
  53858. }
  53859. else {
  53860. sN = (-d + b);
  53861. sD = a;
  53862. }
  53863. }
  53864. // finally do the division to get sc and tc
  53865. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53866. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53867. // get the difference of the two closest points
  53868. var qtc = v.multiplyByFloats(tc, tc, tc);
  53869. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53870. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53871. if (isIntersected) {
  53872. return qtc.length();
  53873. }
  53874. return -1;
  53875. };
  53876. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53877. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53878. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53879. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53880. this.direction.normalize();
  53881. return this;
  53882. };
  53883. // Statics
  53884. Ray.Zero = function () {
  53885. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53886. };
  53887. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53888. var result = Ray.Zero();
  53889. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53890. };
  53891. /**
  53892. * 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
  53893. * transformed to the given world matrix.
  53894. * @param origin The origin point
  53895. * @param end The end point
  53896. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53897. */
  53898. Ray.CreateNewFromTo = function (origin, end, world) {
  53899. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53900. var direction = end.subtract(origin);
  53901. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53902. direction.normalize();
  53903. return Ray.Transform(new Ray(origin, direction, length), world);
  53904. };
  53905. Ray.Transform = function (ray, matrix) {
  53906. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53907. Ray.TransformToRef(ray, matrix, result);
  53908. return result;
  53909. };
  53910. Ray.TransformToRef = function (ray, matrix, result) {
  53911. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53912. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53913. result.length = ray.length;
  53914. var dir = result.direction;
  53915. var len = dir.length();
  53916. if (!(len === 0 || len === 1)) {
  53917. var num = 1.0 / len;
  53918. dir.x *= num;
  53919. dir.y *= num;
  53920. dir.z *= num;
  53921. result.length *= len;
  53922. }
  53923. };
  53924. Ray.smallnum = 0.00000001;
  53925. Ray.rayl = 10e8;
  53926. return Ray;
  53927. }());
  53928. BABYLON.Ray = Ray;
  53929. })(BABYLON || (BABYLON = {}));
  53930. //# sourceMappingURL=babylon.ray.js.map
  53931. var BABYLON;
  53932. (function (BABYLON) {
  53933. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53934. if (boxMin.x > sphereCenter.x + sphereRadius)
  53935. return false;
  53936. if (sphereCenter.x - sphereRadius > boxMax.x)
  53937. return false;
  53938. if (boxMin.y > sphereCenter.y + sphereRadius)
  53939. return false;
  53940. if (sphereCenter.y - sphereRadius > boxMax.y)
  53941. return false;
  53942. if (boxMin.z > sphereCenter.z + sphereRadius)
  53943. return false;
  53944. if (sphereCenter.z - sphereRadius > boxMax.z)
  53945. return false;
  53946. return true;
  53947. };
  53948. var getLowestRoot = (function () {
  53949. var result = { root: 0, found: false };
  53950. return function (a, b, c, maxR) {
  53951. result.root = 0;
  53952. result.found = false;
  53953. var determinant = b * b - 4.0 * a * c;
  53954. if (determinant < 0)
  53955. return result;
  53956. var sqrtD = Math.sqrt(determinant);
  53957. var r1 = (-b - sqrtD) / (2.0 * a);
  53958. var r2 = (-b + sqrtD) / (2.0 * a);
  53959. if (r1 > r2) {
  53960. var temp = r2;
  53961. r2 = r1;
  53962. r1 = temp;
  53963. }
  53964. if (r1 > 0 && r1 < maxR) {
  53965. result.root = r1;
  53966. result.found = true;
  53967. return result;
  53968. }
  53969. if (r2 > 0 && r2 < maxR) {
  53970. result.root = r2;
  53971. result.found = true;
  53972. return result;
  53973. }
  53974. return result;
  53975. };
  53976. })();
  53977. var Collider = /** @class */ (function () {
  53978. function Collider() {
  53979. this._collisionPoint = BABYLON.Vector3.Zero();
  53980. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53981. this._tempVector = BABYLON.Vector3.Zero();
  53982. this._tempVector2 = BABYLON.Vector3.Zero();
  53983. this._tempVector3 = BABYLON.Vector3.Zero();
  53984. this._tempVector4 = BABYLON.Vector3.Zero();
  53985. this._edge = BABYLON.Vector3.Zero();
  53986. this._baseToVertex = BABYLON.Vector3.Zero();
  53987. this._destinationPoint = BABYLON.Vector3.Zero();
  53988. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53989. this._displacementVector = BABYLON.Vector3.Zero();
  53990. this._radius = BABYLON.Vector3.One();
  53991. this._retry = 0;
  53992. this._basePointWorld = BABYLON.Vector3.Zero();
  53993. this._velocityWorld = BABYLON.Vector3.Zero();
  53994. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53995. this._collisionMask = -1;
  53996. }
  53997. Object.defineProperty(Collider.prototype, "collisionMask", {
  53998. get: function () {
  53999. return this._collisionMask;
  54000. },
  54001. set: function (mask) {
  54002. this._collisionMask = !isNaN(mask) ? mask : -1;
  54003. },
  54004. enumerable: true,
  54005. configurable: true
  54006. });
  54007. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54008. /**
  54009. * Gets the plane normal used to compute the sliding response (in local space)
  54010. */
  54011. get: function () {
  54012. return this._slidePlaneNormal;
  54013. },
  54014. enumerable: true,
  54015. configurable: true
  54016. });
  54017. // Methods
  54018. Collider.prototype._initialize = function (source, dir, e) {
  54019. this._velocity = dir;
  54020. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54021. this._basePoint = source;
  54022. source.multiplyToRef(this._radius, this._basePointWorld);
  54023. dir.multiplyToRef(this._radius, this._velocityWorld);
  54024. this._velocityWorldLength = this._velocityWorld.length();
  54025. this._epsilon = e;
  54026. this.collisionFound = false;
  54027. };
  54028. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54029. pa.subtractToRef(point, this._tempVector);
  54030. pb.subtractToRef(point, this._tempVector2);
  54031. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54032. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54033. if (d < 0)
  54034. return false;
  54035. pc.subtractToRef(point, this._tempVector3);
  54036. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54037. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54038. if (d < 0)
  54039. return false;
  54040. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54041. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54042. return d >= 0;
  54043. };
  54044. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54045. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54046. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54047. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54048. return false;
  54049. }
  54050. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54051. return false;
  54052. return true;
  54053. };
  54054. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54055. var t0;
  54056. var embeddedInPlane = false;
  54057. //defensive programming, actually not needed.
  54058. if (!trianglePlaneArray) {
  54059. trianglePlaneArray = [];
  54060. }
  54061. if (!trianglePlaneArray[faceIndex]) {
  54062. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54063. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54064. }
  54065. var trianglePlane = trianglePlaneArray[faceIndex];
  54066. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54067. return;
  54068. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54069. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54070. if (normalDotVelocity == 0) {
  54071. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54072. return;
  54073. embeddedInPlane = true;
  54074. t0 = 0;
  54075. }
  54076. else {
  54077. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54078. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54079. if (t0 > t1) {
  54080. var temp = t1;
  54081. t1 = t0;
  54082. t0 = temp;
  54083. }
  54084. if (t0 > 1.0 || t1 < 0.0)
  54085. return;
  54086. if (t0 < 0)
  54087. t0 = 0;
  54088. if (t0 > 1.0)
  54089. t0 = 1.0;
  54090. }
  54091. this._collisionPoint.copyFromFloats(0, 0, 0);
  54092. var found = false;
  54093. var t = 1.0;
  54094. if (!embeddedInPlane) {
  54095. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54096. this._velocity.scaleToRef(t0, this._tempVector);
  54097. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54098. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54099. found = true;
  54100. t = t0;
  54101. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54102. }
  54103. }
  54104. if (!found) {
  54105. var velocitySquaredLength = this._velocity.lengthSquared();
  54106. var a = velocitySquaredLength;
  54107. this._basePoint.subtractToRef(p1, this._tempVector);
  54108. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54109. var c = this._tempVector.lengthSquared() - 1.0;
  54110. var lowestRoot = getLowestRoot(a, b, c, t);
  54111. if (lowestRoot.found) {
  54112. t = lowestRoot.root;
  54113. found = true;
  54114. this._collisionPoint.copyFrom(p1);
  54115. }
  54116. this._basePoint.subtractToRef(p2, this._tempVector);
  54117. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54118. c = this._tempVector.lengthSquared() - 1.0;
  54119. lowestRoot = getLowestRoot(a, b, c, t);
  54120. if (lowestRoot.found) {
  54121. t = lowestRoot.root;
  54122. found = true;
  54123. this._collisionPoint.copyFrom(p2);
  54124. }
  54125. this._basePoint.subtractToRef(p3, this._tempVector);
  54126. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54127. c = this._tempVector.lengthSquared() - 1.0;
  54128. lowestRoot = getLowestRoot(a, b, c, t);
  54129. if (lowestRoot.found) {
  54130. t = lowestRoot.root;
  54131. found = true;
  54132. this._collisionPoint.copyFrom(p3);
  54133. }
  54134. p2.subtractToRef(p1, this._edge);
  54135. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54136. var edgeSquaredLength = this._edge.lengthSquared();
  54137. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54138. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54139. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54140. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54141. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54142. lowestRoot = getLowestRoot(a, b, c, t);
  54143. if (lowestRoot.found) {
  54144. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54145. if (f >= 0.0 && f <= 1.0) {
  54146. t = lowestRoot.root;
  54147. found = true;
  54148. this._edge.scaleInPlace(f);
  54149. p1.addToRef(this._edge, this._collisionPoint);
  54150. }
  54151. }
  54152. p3.subtractToRef(p2, this._edge);
  54153. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54154. edgeSquaredLength = this._edge.lengthSquared();
  54155. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54156. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54157. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54158. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54159. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54160. lowestRoot = getLowestRoot(a, b, c, t);
  54161. if (lowestRoot.found) {
  54162. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54163. if (f >= 0.0 && f <= 1.0) {
  54164. t = lowestRoot.root;
  54165. found = true;
  54166. this._edge.scaleInPlace(f);
  54167. p2.addToRef(this._edge, this._collisionPoint);
  54168. }
  54169. }
  54170. p1.subtractToRef(p3, this._edge);
  54171. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54172. edgeSquaredLength = this._edge.lengthSquared();
  54173. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54174. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54175. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54176. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54177. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54178. lowestRoot = getLowestRoot(a, b, c, t);
  54179. if (lowestRoot.found) {
  54180. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54181. if (f >= 0.0 && f <= 1.0) {
  54182. t = lowestRoot.root;
  54183. found = true;
  54184. this._edge.scaleInPlace(f);
  54185. p3.addToRef(this._edge, this._collisionPoint);
  54186. }
  54187. }
  54188. }
  54189. if (found) {
  54190. var distToCollision = t * this._velocity.length();
  54191. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54192. if (!this.intersectionPoint) {
  54193. this.intersectionPoint = this._collisionPoint.clone();
  54194. }
  54195. else {
  54196. this.intersectionPoint.copyFrom(this._collisionPoint);
  54197. }
  54198. this._nearestDistance = distToCollision;
  54199. this.collisionFound = true;
  54200. }
  54201. }
  54202. };
  54203. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54204. for (var i = indexStart; i < indexEnd; i += 3) {
  54205. var p1 = pts[indices[i] - decal];
  54206. var p2 = pts[indices[i + 1] - decal];
  54207. var p3 = pts[indices[i + 2] - decal];
  54208. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54209. }
  54210. };
  54211. Collider.prototype._getResponse = function (pos, vel) {
  54212. pos.addToRef(vel, this._destinationPoint);
  54213. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54214. this._basePoint.addToRef(vel, pos);
  54215. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54216. this._slidePlaneNormal.normalize();
  54217. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54218. pos.addInPlace(this._displacementVector);
  54219. this.intersectionPoint.addInPlace(this._displacementVector);
  54220. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54221. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54222. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54223. };
  54224. return Collider;
  54225. }());
  54226. BABYLON.Collider = Collider;
  54227. })(BABYLON || (BABYLON = {}));
  54228. //# sourceMappingURL=babylon.collider.js.map
  54229. var BABYLON;
  54230. (function (BABYLON) {
  54231. //WebWorker code will be inserted to this variable.
  54232. BABYLON.CollisionWorker = "";
  54233. var WorkerTaskType;
  54234. (function (WorkerTaskType) {
  54235. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54236. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54237. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54238. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54239. var WorkerReplyType;
  54240. (function (WorkerReplyType) {
  54241. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54242. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54243. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54244. var CollisionCoordinatorWorker = /** @class */ (function () {
  54245. function CollisionCoordinatorWorker() {
  54246. var _this = this;
  54247. this._scaledPosition = BABYLON.Vector3.Zero();
  54248. this._scaledVelocity = BABYLON.Vector3.Zero();
  54249. this.onMeshUpdated = function (transformNode) {
  54250. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54251. };
  54252. this.onGeometryUpdated = function (geometry) {
  54253. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54254. };
  54255. this._afterRender = function () {
  54256. if (!_this._init)
  54257. return;
  54258. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54259. return;
  54260. }
  54261. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54262. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54263. if (_this._runningUpdated > 4) {
  54264. return;
  54265. }
  54266. ++_this._runningUpdated;
  54267. var payload = {
  54268. updatedMeshes: _this._addUpdateMeshesList,
  54269. updatedGeometries: _this._addUpdateGeometriesList,
  54270. removedGeometries: _this._toRemoveGeometryArray,
  54271. removedMeshes: _this._toRemoveMeshesArray
  54272. };
  54273. var message = {
  54274. payload: payload,
  54275. taskType: WorkerTaskType.UPDATE
  54276. };
  54277. var serializable = [];
  54278. for (var id in payload.updatedGeometries) {
  54279. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54280. //prepare transferables
  54281. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54282. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54283. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54284. }
  54285. }
  54286. _this._worker.postMessage(message, serializable);
  54287. _this._addUpdateMeshesList = {};
  54288. _this._addUpdateGeometriesList = {};
  54289. _this._toRemoveGeometryArray = [];
  54290. _this._toRemoveMeshesArray = [];
  54291. };
  54292. this._onMessageFromWorker = function (e) {
  54293. var returnData = e.data;
  54294. if (returnData.error != WorkerReplyType.SUCCESS) {
  54295. //TODO what errors can be returned from the worker?
  54296. BABYLON.Tools.Warn("error returned from worker!");
  54297. return;
  54298. }
  54299. switch (returnData.taskType) {
  54300. case WorkerTaskType.INIT:
  54301. _this._init = true;
  54302. //Update the worked with ALL of the scene's current state
  54303. _this._scene.meshes.forEach(function (mesh) {
  54304. _this.onMeshAdded(mesh);
  54305. });
  54306. _this._scene.getGeometries().forEach(function (geometry) {
  54307. _this.onGeometryAdded(geometry);
  54308. });
  54309. break;
  54310. case WorkerTaskType.UPDATE:
  54311. _this._runningUpdated--;
  54312. break;
  54313. case WorkerTaskType.COLLIDE:
  54314. var returnPayload = returnData.payload;
  54315. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54316. return;
  54317. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54318. if (callback) {
  54319. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54320. if (mesh) {
  54321. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54322. }
  54323. }
  54324. //cleanup
  54325. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54326. break;
  54327. }
  54328. };
  54329. this._collisionsCallbackArray = [];
  54330. this._init = false;
  54331. this._runningUpdated = 0;
  54332. this._addUpdateMeshesList = {};
  54333. this._addUpdateGeometriesList = {};
  54334. this._toRemoveGeometryArray = [];
  54335. this._toRemoveMeshesArray = [];
  54336. }
  54337. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54338. if (!this._init)
  54339. return;
  54340. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54341. return;
  54342. position.divideToRef(collider._radius, this._scaledPosition);
  54343. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54344. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54345. var payload = {
  54346. collider: {
  54347. position: this._scaledPosition.asArray(),
  54348. velocity: this._scaledVelocity.asArray(),
  54349. radius: collider._radius.asArray()
  54350. },
  54351. collisionId: collisionIndex,
  54352. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54353. maximumRetry: maximumRetry
  54354. };
  54355. var message = {
  54356. payload: payload,
  54357. taskType: WorkerTaskType.COLLIDE
  54358. };
  54359. this._worker.postMessage(message);
  54360. };
  54361. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54362. this._scene = scene;
  54363. this._scene.registerAfterRender(this._afterRender);
  54364. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54365. this._worker = new Worker(workerUrl);
  54366. this._worker.onmessage = this._onMessageFromWorker;
  54367. var message = {
  54368. payload: {},
  54369. taskType: WorkerTaskType.INIT
  54370. };
  54371. this._worker.postMessage(message);
  54372. };
  54373. CollisionCoordinatorWorker.prototype.destroy = function () {
  54374. this._scene.unregisterAfterRender(this._afterRender);
  54375. this._worker.terminate();
  54376. };
  54377. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54378. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54379. this.onMeshUpdated(mesh);
  54380. };
  54381. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54382. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54383. };
  54384. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54385. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54386. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54387. this.onGeometryUpdated(geometry);
  54388. };
  54389. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54390. this._toRemoveGeometryArray.push(geometry.id);
  54391. };
  54392. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54393. var submeshes = [];
  54394. if (mesh.subMeshes) {
  54395. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54396. var boundingInfo = sm.getBoundingInfo();
  54397. return {
  54398. position: idx,
  54399. verticesStart: sm.verticesStart,
  54400. verticesCount: sm.verticesCount,
  54401. indexStart: sm.indexStart,
  54402. indexCount: sm.indexCount,
  54403. hasMaterial: !!sm.getMaterial(),
  54404. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54405. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54406. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54407. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54408. };
  54409. });
  54410. }
  54411. var geometryId = null;
  54412. if (mesh instanceof BABYLON.Mesh) {
  54413. var geometry = mesh.geometry;
  54414. geometryId = geometry ? geometry.id : null;
  54415. }
  54416. else if (mesh instanceof BABYLON.InstancedMesh) {
  54417. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54418. geometryId = geometry ? geometry.id : null;
  54419. }
  54420. var boundingInfo = mesh.getBoundingInfo();
  54421. return {
  54422. uniqueId: mesh.uniqueId,
  54423. id: mesh.id,
  54424. name: mesh.name,
  54425. geometryId: geometryId,
  54426. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54427. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54428. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54429. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54430. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54431. subMeshes: submeshes,
  54432. checkCollisions: mesh.checkCollisions
  54433. };
  54434. };
  54435. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54436. return {
  54437. id: geometry.id,
  54438. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54439. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54440. indices: new Uint32Array(geometry.getIndices() || []),
  54441. };
  54442. };
  54443. return CollisionCoordinatorWorker;
  54444. }());
  54445. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54446. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54447. function CollisionCoordinatorLegacy() {
  54448. this._scaledPosition = BABYLON.Vector3.Zero();
  54449. this._scaledVelocity = BABYLON.Vector3.Zero();
  54450. this._finalPosition = BABYLON.Vector3.Zero();
  54451. }
  54452. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54453. position.divideToRef(collider._radius, this._scaledPosition);
  54454. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54455. collider.collidedMesh = null;
  54456. collider._retry = 0;
  54457. collider._initialVelocity = this._scaledVelocity;
  54458. collider._initialPosition = this._scaledPosition;
  54459. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54460. this._finalPosition.multiplyInPlace(collider._radius);
  54461. //run the callback
  54462. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54463. };
  54464. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54465. this._scene = scene;
  54466. };
  54467. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54468. //Legacy need no destruction method.
  54469. };
  54470. //No update in legacy mode
  54471. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54472. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54473. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54474. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54475. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54476. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54477. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54478. if (excludedMesh === void 0) { excludedMesh = null; }
  54479. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54480. if (collider._retry >= maximumRetry) {
  54481. finalPosition.copyFrom(position);
  54482. return;
  54483. }
  54484. // Check if this is a mesh else camera or -1
  54485. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54486. collider._initialize(position, velocity, closeDistance);
  54487. // Check all meshes
  54488. for (var index = 0; index < this._scene.meshes.length; index++) {
  54489. var mesh = this._scene.meshes[index];
  54490. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54491. mesh._checkCollision(collider);
  54492. }
  54493. }
  54494. if (!collider.collisionFound) {
  54495. position.addToRef(velocity, finalPosition);
  54496. return;
  54497. }
  54498. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54499. collider._getResponse(position, velocity);
  54500. }
  54501. if (velocity.length() <= closeDistance) {
  54502. finalPosition.copyFrom(position);
  54503. return;
  54504. }
  54505. collider._retry++;
  54506. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54507. };
  54508. return CollisionCoordinatorLegacy;
  54509. }());
  54510. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54511. })(BABYLON || (BABYLON = {}));
  54512. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54513. var BABYLON;
  54514. (function (BABYLON) {
  54515. /**
  54516. * A particle represents one of the element emitted by a particle system.
  54517. * This is mainly define by its coordinates, direction, velocity and age.
  54518. */
  54519. var Particle = /** @class */ (function () {
  54520. /**
  54521. * Creates a new instance Particle
  54522. * @param particleSystem the particle system the particle belongs to
  54523. */
  54524. function Particle(
  54525. /**
  54526. * particleSystem the particle system the particle belongs to.
  54527. */
  54528. particleSystem) {
  54529. this.particleSystem = particleSystem;
  54530. /**
  54531. * The world position of the particle in the scene.
  54532. */
  54533. this.position = BABYLON.Vector3.Zero();
  54534. /**
  54535. * The world direction of the particle in the scene.
  54536. */
  54537. this.direction = BABYLON.Vector3.Zero();
  54538. /**
  54539. * The color of the particle.
  54540. */
  54541. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54542. /**
  54543. * The color change of the particle per step.
  54544. */
  54545. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54546. /**
  54547. * Defines how long will the life of the particle be.
  54548. */
  54549. this.lifeTime = 1.0;
  54550. /**
  54551. * The current age of the particle.
  54552. */
  54553. this.age = 0;
  54554. /**
  54555. * The current size of the particle.
  54556. */
  54557. this.size = 0;
  54558. /**
  54559. * The current angle of the particle.
  54560. */
  54561. this.angle = 0;
  54562. /**
  54563. * Defines how fast is the angle changing.
  54564. */
  54565. this.angularSpeed = 0;
  54566. /**
  54567. * Defines the cell index used by the particle to be rendered from a sprite.
  54568. */
  54569. this.cellIndex = 0;
  54570. this._currentFrameCounter = 0;
  54571. if (!this.particleSystem.isAnimationSheetEnabled) {
  54572. return;
  54573. }
  54574. this.updateCellInfoFromSystem();
  54575. }
  54576. Particle.prototype.updateCellInfoFromSystem = function () {
  54577. this.cellIndex = this.particleSystem.startSpriteCellID;
  54578. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54579. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54580. }
  54581. else {
  54582. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54583. }
  54584. };
  54585. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54586. // (ageOffset / scaledUpdateSpeed) / available cells
  54587. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54588. this._currentFrameCounter += scaledUpdateSpeed;
  54589. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54590. this._currentFrameCounter = 0;
  54591. this.cellIndex++;
  54592. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54593. this.cellIndex = this.particleSystem.endSpriteCellID;
  54594. }
  54595. }
  54596. };
  54597. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54598. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54599. this.cellIndex++;
  54600. this._currentFrameCounter = 0;
  54601. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54602. if (this.particleSystem.spriteCellLoop) {
  54603. this.cellIndex = this.particleSystem.startSpriteCellID;
  54604. }
  54605. else {
  54606. this.cellIndex = this.particleSystem.endSpriteCellID;
  54607. }
  54608. }
  54609. }
  54610. else {
  54611. this._currentFrameCounter++;
  54612. }
  54613. };
  54614. /**
  54615. * Copy the properties of particle to another one.
  54616. * @param other the particle to copy the information to.
  54617. */
  54618. Particle.prototype.copyTo = function (other) {
  54619. other.position.copyFrom(this.position);
  54620. other.direction.copyFrom(this.direction);
  54621. other.color.copyFrom(this.color);
  54622. other.colorStep.copyFrom(this.colorStep);
  54623. other.lifeTime = this.lifeTime;
  54624. other.age = this.age;
  54625. other.size = this.size;
  54626. other.angle = this.angle;
  54627. other.angularSpeed = this.angularSpeed;
  54628. other.particleSystem = this.particleSystem;
  54629. other.cellIndex = this.cellIndex;
  54630. };
  54631. return Particle;
  54632. }());
  54633. BABYLON.Particle = Particle;
  54634. })(BABYLON || (BABYLON = {}));
  54635. //# sourceMappingURL=babylon.particle.js.map
  54636. var BABYLON;
  54637. (function (BABYLON) {
  54638. /**
  54639. * This represents a particle system in Babylon.
  54640. * 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.
  54641. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54642. * @example https://doc.babylonjs.com/babylon101/particles
  54643. */
  54644. var ParticleSystem = /** @class */ (function () {
  54645. /**
  54646. * Instantiates a particle system.
  54647. * 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.
  54648. * @param name The name of the particle system
  54649. * @param capacity The max number of particles alive at the same time
  54650. * @param scene The scene the particle system belongs to
  54651. * @param customEffect a custom effect used to change the way particles are rendered by default
  54652. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54653. * @param epsilon Offset used to render the particles
  54654. */
  54655. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54656. if (customEffect === void 0) { customEffect = null; }
  54657. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54658. if (epsilon === void 0) { epsilon = 0.01; }
  54659. var _this = this;
  54660. /**
  54661. * List of animations used by the particle system.
  54662. */
  54663. this.animations = [];
  54664. /**
  54665. * The rendering group used by the Particle system to chose when to render.
  54666. */
  54667. this.renderingGroupId = 0;
  54668. /**
  54669. * The emitter represents the Mesh or position we are attaching the particle system to.
  54670. */
  54671. this.emitter = null;
  54672. /**
  54673. * The maximum number of particles to emit per frame
  54674. */
  54675. this.emitRate = 10;
  54676. /**
  54677. * If you want to launch only a few particles at once, that can be done, as well.
  54678. */
  54679. this.manualEmitCount = -1;
  54680. /**
  54681. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54682. */
  54683. this.updateSpeed = 0.01;
  54684. /**
  54685. * The amount of time the particle system is running (depends of the overall update speed).
  54686. */
  54687. this.targetStopDuration = 0;
  54688. /**
  54689. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54690. */
  54691. this.disposeOnStop = false;
  54692. /**
  54693. * Minimum power of emitting particles.
  54694. */
  54695. this.minEmitPower = 1;
  54696. /**
  54697. * Maximum power of emitting particles.
  54698. */
  54699. this.maxEmitPower = 1;
  54700. /**
  54701. * Minimum life time of emitting particles.
  54702. */
  54703. this.minLifeTime = 1;
  54704. /**
  54705. * Maximum life time of emitting particles.
  54706. */
  54707. this.maxLifeTime = 1;
  54708. /**
  54709. * Minimum Size of emitting particles.
  54710. */
  54711. this.minSize = 1;
  54712. /**
  54713. * Maximum Size of emitting particles.
  54714. */
  54715. this.maxSize = 1;
  54716. /**
  54717. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54718. */
  54719. this.minAngularSpeed = 0;
  54720. /**
  54721. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54722. */
  54723. this.maxAngularSpeed = 0;
  54724. /**
  54725. * The layer mask we are rendering the particles through.
  54726. */
  54727. this.layerMask = 0x0FFFFFFF;
  54728. /**
  54729. * This can help using your own shader to render the particle system.
  54730. * The according effect will be created
  54731. */
  54732. this.customShader = null;
  54733. /**
  54734. * By default particle system starts as soon as they are created. This prevents the
  54735. * automatic start to happen and let you decide when to start emitting particles.
  54736. */
  54737. this.preventAutoStart = false;
  54738. /**
  54739. * Callback triggered when the particle animation is ending.
  54740. */
  54741. this.onAnimationEnd = null;
  54742. /**
  54743. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54744. */
  54745. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54746. /**
  54747. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54748. * to override the particles.
  54749. */
  54750. this.forceDepthWrite = false;
  54751. /**
  54752. * You can use gravity if you want to give an orientation to your particles.
  54753. */
  54754. this.gravity = BABYLON.Vector3.Zero();
  54755. /**
  54756. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54757. */
  54758. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54759. /**
  54760. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54761. */
  54762. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54763. /**
  54764. * Color the particle will have at the end of its lifetime.
  54765. */
  54766. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54767. /**
  54768. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54769. */
  54770. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54771. /**
  54772. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54773. */
  54774. this.spriteCellLoop = true;
  54775. /**
  54776. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54777. */
  54778. this.spriteCellChangeSpeed = 0;
  54779. /**
  54780. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54781. */
  54782. this.startSpriteCellID = 0;
  54783. /**
  54784. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54785. */
  54786. this.endSpriteCellID = 0;
  54787. /**
  54788. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54789. */
  54790. this.spriteCellWidth = 0;
  54791. /**
  54792. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54793. */
  54794. this.spriteCellHeight = 0;
  54795. /**
  54796. * An event triggered when the system is disposed.
  54797. */
  54798. this.onDisposeObservable = new BABYLON.Observable();
  54799. this._particles = new Array();
  54800. this._stockParticles = new Array();
  54801. this._newPartsExcess = 0;
  54802. this._vertexBuffers = {};
  54803. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54804. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54805. this._scaledDirection = BABYLON.Vector3.Zero();
  54806. this._scaledGravity = BABYLON.Vector3.Zero();
  54807. this._currentRenderId = -1;
  54808. this._started = false;
  54809. this._stopped = false;
  54810. this._actualFrame = 0;
  54811. this._vertexBufferSize = 11;
  54812. // start of sub system methods
  54813. /**
  54814. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54815. * Its lifetime will start back at 0.
  54816. */
  54817. this.recycleParticle = function (particle) {
  54818. var lastParticle = _this._particles.pop();
  54819. if (lastParticle !== particle) {
  54820. lastParticle.copyTo(particle);
  54821. }
  54822. _this._stockParticles.push(lastParticle);
  54823. };
  54824. this._createParticle = function () {
  54825. var particle;
  54826. if (_this._stockParticles.length !== 0) {
  54827. particle = _this._stockParticles.pop();
  54828. particle.age = 0;
  54829. particle.cellIndex = _this.startSpriteCellID;
  54830. }
  54831. else {
  54832. particle = new BABYLON.Particle(_this);
  54833. }
  54834. return particle;
  54835. };
  54836. this._emitFromParticle = function (particle) {
  54837. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54838. return;
  54839. }
  54840. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54841. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54842. subSystem._rootParticleSystem = _this;
  54843. _this.activeSubSystems.push(subSystem);
  54844. subSystem.start();
  54845. };
  54846. this._appendParticleVertexes = null;
  54847. this.id = name;
  54848. this.name = name;
  54849. this._capacity = capacity;
  54850. this._epsilon = epsilon;
  54851. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54852. if (isAnimationSheetEnabled) {
  54853. this._vertexBufferSize = 12;
  54854. }
  54855. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54856. this._customEffect = customEffect;
  54857. scene.particleSystems.push(this);
  54858. this._createIndexBuffer();
  54859. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54860. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54861. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54862. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54863. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54864. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54865. if (this._isAnimationSheetEnabled) {
  54866. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54867. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54868. }
  54869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54870. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54871. this._vertexBuffers["options"] = options;
  54872. // Default emitter type
  54873. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54874. this.updateFunction = function (particles) {
  54875. for (var index = 0; index < particles.length; index++) {
  54876. var particle = particles[index];
  54877. particle.age += _this._scaledUpdateSpeed;
  54878. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  54879. _this._emitFromParticle(particle);
  54880. _this.recycleParticle(particle);
  54881. index--;
  54882. continue;
  54883. }
  54884. else {
  54885. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54886. particle.color.addInPlace(_this._scaledColorStep);
  54887. if (particle.color.a < 0)
  54888. particle.color.a = 0;
  54889. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54890. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54891. particle.position.addInPlace(_this._scaledDirection);
  54892. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54893. particle.direction.addInPlace(_this._scaledGravity);
  54894. if (_this._isAnimationSheetEnabled) {
  54895. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54896. }
  54897. }
  54898. }
  54899. };
  54900. }
  54901. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54902. /**
  54903. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54904. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54905. */
  54906. get: function () {
  54907. if (this.particleEmitterType.direction1) {
  54908. return this.particleEmitterType.direction1;
  54909. }
  54910. return BABYLON.Vector3.Zero();
  54911. },
  54912. set: function (value) {
  54913. if (this.particleEmitterType.direction1) {
  54914. this.particleEmitterType.direction1 = value;
  54915. }
  54916. },
  54917. enumerable: true,
  54918. configurable: true
  54919. });
  54920. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54921. /**
  54922. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54924. */
  54925. get: function () {
  54926. if (this.particleEmitterType.direction2) {
  54927. return this.particleEmitterType.direction2;
  54928. }
  54929. return BABYLON.Vector3.Zero();
  54930. },
  54931. set: function (value) {
  54932. if (this.particleEmitterType.direction2) {
  54933. this.particleEmitterType.direction2 = value;
  54934. }
  54935. },
  54936. enumerable: true,
  54937. configurable: true
  54938. });
  54939. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54940. /**
  54941. * 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.
  54942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54943. */
  54944. get: function () {
  54945. if (this.particleEmitterType.minEmitBox) {
  54946. return this.particleEmitterType.minEmitBox;
  54947. }
  54948. return BABYLON.Vector3.Zero();
  54949. },
  54950. set: function (value) {
  54951. if (this.particleEmitterType.minEmitBox) {
  54952. this.particleEmitterType.minEmitBox = value;
  54953. }
  54954. },
  54955. enumerable: true,
  54956. configurable: true
  54957. });
  54958. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54959. /**
  54960. * 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.
  54961. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54962. */
  54963. get: function () {
  54964. if (this.particleEmitterType.maxEmitBox) {
  54965. return this.particleEmitterType.maxEmitBox;
  54966. }
  54967. return BABYLON.Vector3.Zero();
  54968. },
  54969. set: function (value) {
  54970. if (this.particleEmitterType.maxEmitBox) {
  54971. this.particleEmitterType.maxEmitBox = value;
  54972. }
  54973. },
  54974. enumerable: true,
  54975. configurable: true
  54976. });
  54977. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54978. /**
  54979. * Sets a callback that will be triggered when the system is disposed.
  54980. */
  54981. set: function (callback) {
  54982. if (this._onDisposeObserver) {
  54983. this.onDisposeObservable.remove(this._onDisposeObserver);
  54984. }
  54985. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54986. },
  54987. enumerable: true,
  54988. configurable: true
  54989. });
  54990. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54991. /**
  54992. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54993. */
  54994. get: function () {
  54995. return this._isAnimationSheetEnabled;
  54996. },
  54997. enumerable: true,
  54998. configurable: true
  54999. });
  55000. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55001. //end of Sub-emitter
  55002. /**
  55003. * Gets the current list of active particles
  55004. */
  55005. get: function () {
  55006. return this._particles;
  55007. },
  55008. enumerable: true,
  55009. configurable: true
  55010. });
  55011. /**
  55012. * Returns the string "ParticleSystem"
  55013. * @returns a string containing the class name
  55014. */
  55015. ParticleSystem.prototype.getClassName = function () {
  55016. return "ParticleSystem";
  55017. };
  55018. ParticleSystem.prototype._createIndexBuffer = function () {
  55019. var indices = [];
  55020. var index = 0;
  55021. for (var count = 0; count < this._capacity; count++) {
  55022. indices.push(index);
  55023. indices.push(index + 1);
  55024. indices.push(index + 2);
  55025. indices.push(index);
  55026. indices.push(index + 2);
  55027. indices.push(index + 3);
  55028. index += 4;
  55029. }
  55030. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55031. };
  55032. /**
  55033. * Gets the maximum number of particles active at the same time.
  55034. * @returns The max number of active particles.
  55035. */
  55036. ParticleSystem.prototype.getCapacity = function () {
  55037. return this._capacity;
  55038. };
  55039. /**
  55040. * Gets Wether there are still active particles in the system.
  55041. * @returns True if it is alive, otherwise false.
  55042. */
  55043. ParticleSystem.prototype.isAlive = function () {
  55044. return this._alive;
  55045. };
  55046. /**
  55047. * Gets Wether the system has been started.
  55048. * @returns True if it has been started, otherwise false.
  55049. */
  55050. ParticleSystem.prototype.isStarted = function () {
  55051. return this._started;
  55052. };
  55053. /**
  55054. * Starts the particle system and begins to emit.
  55055. */
  55056. ParticleSystem.prototype.start = function () {
  55057. this._started = true;
  55058. this._stopped = false;
  55059. this._actualFrame = 0;
  55060. if (this.subEmitters && this.subEmitters.length != 0) {
  55061. this.activeSubSystems = new Array();
  55062. }
  55063. };
  55064. /**
  55065. * Stops the particle system.
  55066. * @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.
  55067. */
  55068. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55069. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55070. this._stopped = true;
  55071. if (stopSubEmitters) {
  55072. this._stopSubEmitters();
  55073. }
  55074. };
  55075. // animation sheet
  55076. /**
  55077. * Remove all active particles
  55078. */
  55079. ParticleSystem.prototype.reset = function () {
  55080. this._stockParticles = [];
  55081. this._particles = [];
  55082. };
  55083. /**
  55084. * @ignore (for internal use only)
  55085. */
  55086. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55087. var offset = index * this._vertexBufferSize;
  55088. this._vertexData[offset] = particle.position.x;
  55089. this._vertexData[offset + 1] = particle.position.y;
  55090. this._vertexData[offset + 2] = particle.position.z;
  55091. this._vertexData[offset + 3] = particle.color.r;
  55092. this._vertexData[offset + 4] = particle.color.g;
  55093. this._vertexData[offset + 5] = particle.color.b;
  55094. this._vertexData[offset + 6] = particle.color.a;
  55095. this._vertexData[offset + 7] = particle.angle;
  55096. this._vertexData[offset + 8] = particle.size;
  55097. this._vertexData[offset + 9] = offsetX;
  55098. this._vertexData[offset + 10] = offsetY;
  55099. };
  55100. /**
  55101. * @ignore (for internal use only)
  55102. */
  55103. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55104. if (offsetX === 0)
  55105. offsetX = this._epsilon;
  55106. else if (offsetX === 1)
  55107. offsetX = 1 - this._epsilon;
  55108. if (offsetY === 0)
  55109. offsetY = this._epsilon;
  55110. else if (offsetY === 1)
  55111. offsetY = 1 - this._epsilon;
  55112. var offset = index * this._vertexBufferSize;
  55113. this._vertexData[offset] = particle.position.x;
  55114. this._vertexData[offset + 1] = particle.position.y;
  55115. this._vertexData[offset + 2] = particle.position.z;
  55116. this._vertexData[offset + 3] = particle.color.r;
  55117. this._vertexData[offset + 4] = particle.color.g;
  55118. this._vertexData[offset + 5] = particle.color.b;
  55119. this._vertexData[offset + 6] = particle.color.a;
  55120. this._vertexData[offset + 7] = particle.angle;
  55121. this._vertexData[offset + 8] = particle.size;
  55122. this._vertexData[offset + 9] = offsetX;
  55123. this._vertexData[offset + 10] = offsetY;
  55124. this._vertexData[offset + 11] = particle.cellIndex;
  55125. };
  55126. ParticleSystem.prototype._stopSubEmitters = function () {
  55127. if (!this.activeSubSystems) {
  55128. return;
  55129. }
  55130. this.activeSubSystems.forEach(function (subSystem) {
  55131. subSystem.stop(true);
  55132. });
  55133. this.activeSubSystems = new Array();
  55134. };
  55135. ParticleSystem.prototype._removeFromRoot = function () {
  55136. if (!this._rootParticleSystem) {
  55137. return;
  55138. }
  55139. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55140. if (index !== -1) {
  55141. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55142. }
  55143. };
  55144. // end of sub system methods
  55145. ParticleSystem.prototype._update = function (newParticles) {
  55146. // Update current
  55147. this._alive = this._particles.length > 0;
  55148. this.updateFunction(this._particles);
  55149. // Add new ones
  55150. var worldMatrix;
  55151. if (this.emitter.position) {
  55152. var emitterMesh = this.emitter;
  55153. worldMatrix = emitterMesh.getWorldMatrix();
  55154. }
  55155. else {
  55156. var emitterPosition = this.emitter;
  55157. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55158. }
  55159. var particle;
  55160. for (var index = 0; index < newParticles; index++) {
  55161. if (this._particles.length === this._capacity) {
  55162. break;
  55163. }
  55164. particle = this._createParticle();
  55165. this._particles.push(particle);
  55166. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55167. if (this.startPositionFunction) {
  55168. this.startPositionFunction(worldMatrix, particle.position, particle);
  55169. }
  55170. else {
  55171. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55172. }
  55173. if (this.startDirectionFunction) {
  55174. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55175. }
  55176. else {
  55177. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55178. }
  55179. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55180. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55181. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55182. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55183. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55184. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55185. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55186. }
  55187. };
  55188. ParticleSystem.prototype._getEffect = function () {
  55189. if (this._customEffect) {
  55190. return this._customEffect;
  55191. }
  55192. ;
  55193. var defines = [];
  55194. if (this._scene.clipPlane) {
  55195. defines.push("#define CLIPPLANE");
  55196. }
  55197. if (this._isAnimationSheetEnabled) {
  55198. defines.push("#define ANIMATESHEET");
  55199. }
  55200. // Effect
  55201. var join = defines.join("\n");
  55202. if (this._cachedDefines !== join) {
  55203. this._cachedDefines = join;
  55204. var attributesNamesOrOptions;
  55205. var effectCreationOption;
  55206. if (this._isAnimationSheetEnabled) {
  55207. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55208. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55209. }
  55210. else {
  55211. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55212. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55213. }
  55214. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55215. }
  55216. return this._effect;
  55217. };
  55218. /**
  55219. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55220. */
  55221. ParticleSystem.prototype.animate = function () {
  55222. if (!this._started)
  55223. return;
  55224. var effect = this._getEffect();
  55225. // Check
  55226. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55227. return;
  55228. if (this._currentRenderId === this._scene.getRenderId()) {
  55229. return;
  55230. }
  55231. this._currentRenderId = this._scene.getRenderId();
  55232. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55233. // determine the number of particles we need to create
  55234. var newParticles;
  55235. if (this.manualEmitCount > -1) {
  55236. newParticles = this.manualEmitCount;
  55237. this._newPartsExcess = 0;
  55238. this.manualEmitCount = 0;
  55239. }
  55240. else {
  55241. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55242. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55243. }
  55244. if (this._newPartsExcess > 1.0) {
  55245. newParticles += this._newPartsExcess >> 0;
  55246. this._newPartsExcess -= this._newPartsExcess >> 0;
  55247. }
  55248. this._alive = false;
  55249. if (!this._stopped) {
  55250. this._actualFrame += this._scaledUpdateSpeed;
  55251. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55252. this.stop();
  55253. }
  55254. else {
  55255. newParticles = 0;
  55256. }
  55257. this._update(newParticles);
  55258. // Stopped?
  55259. if (this._stopped) {
  55260. if (!this._alive) {
  55261. this._started = false;
  55262. if (this.onAnimationEnd) {
  55263. this.onAnimationEnd();
  55264. }
  55265. if (this.disposeOnStop) {
  55266. this._scene._toBeDisposed.push(this);
  55267. }
  55268. }
  55269. }
  55270. // Animation sheet
  55271. if (this._isAnimationSheetEnabled) {
  55272. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55273. }
  55274. else {
  55275. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55276. }
  55277. // Update VBO
  55278. var offset = 0;
  55279. for (var index = 0; index < this._particles.length; index++) {
  55280. var particle = this._particles[index];
  55281. this._appendParticleVertexes(offset, particle);
  55282. offset += 4;
  55283. }
  55284. if (this._vertexBuffer) {
  55285. this._vertexBuffer.update(this._vertexData);
  55286. }
  55287. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55288. this.stop();
  55289. }
  55290. };
  55291. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55292. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55293. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55294. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55295. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55296. };
  55297. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55298. this._appendParticleVertex(offset++, particle, 0, 0);
  55299. this._appendParticleVertex(offset++, particle, 1, 0);
  55300. this._appendParticleVertex(offset++, particle, 1, 1);
  55301. this._appendParticleVertex(offset++, particle, 0, 1);
  55302. };
  55303. /**
  55304. * Rebuilds the particle system.
  55305. */
  55306. ParticleSystem.prototype.rebuild = function () {
  55307. this._createIndexBuffer();
  55308. if (this._vertexBuffer) {
  55309. this._vertexBuffer._rebuild();
  55310. }
  55311. };
  55312. /**
  55313. * Is this system ready to be used/rendered
  55314. * @return true if the system is ready
  55315. */
  55316. ParticleSystem.prototype.isReady = function () {
  55317. var effect = this._getEffect();
  55318. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55319. return false;
  55320. }
  55321. return true;
  55322. };
  55323. /**
  55324. * Renders the particle system in its current state.
  55325. * @returns the current number of particles
  55326. */
  55327. ParticleSystem.prototype.render = function () {
  55328. var effect = this._getEffect();
  55329. // Check
  55330. if (!this.isReady() || !this._particles.length) {
  55331. return 0;
  55332. }
  55333. var engine = this._scene.getEngine();
  55334. // Render
  55335. engine.enableEffect(effect);
  55336. engine.setState(false);
  55337. var viewMatrix = this._scene.getViewMatrix();
  55338. effect.setTexture("diffuseSampler", this.particleTexture);
  55339. effect.setMatrix("view", viewMatrix);
  55340. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55341. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55342. var baseSize = this.particleTexture.getBaseSize();
  55343. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55344. }
  55345. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55346. if (this._scene.clipPlane) {
  55347. var clipPlane = this._scene.clipPlane;
  55348. var invView = viewMatrix.clone();
  55349. invView.invert();
  55350. effect.setMatrix("invView", invView);
  55351. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55352. }
  55353. // VBOs
  55354. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55355. // Draw order
  55356. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55357. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55358. }
  55359. else {
  55360. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55361. }
  55362. if (this.forceDepthWrite) {
  55363. engine.setDepthWrite(true);
  55364. }
  55365. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55366. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55367. return this._particles.length;
  55368. };
  55369. /**
  55370. * Disposes the particle system and free the associated resources
  55371. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55372. */
  55373. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55374. if (disposeTexture === void 0) { disposeTexture = true; }
  55375. if (this._vertexBuffer) {
  55376. this._vertexBuffer.dispose();
  55377. this._vertexBuffer = null;
  55378. }
  55379. if (this._indexBuffer) {
  55380. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55381. this._indexBuffer = null;
  55382. }
  55383. if (disposeTexture && this.particleTexture) {
  55384. this.particleTexture.dispose();
  55385. this.particleTexture = null;
  55386. }
  55387. this._removeFromRoot();
  55388. // Remove from scene
  55389. var index = this._scene.particleSystems.indexOf(this);
  55390. if (index > -1) {
  55391. this._scene.particleSystems.splice(index, 1);
  55392. }
  55393. // Callback
  55394. this.onDisposeObservable.notifyObservers(this);
  55395. this.onDisposeObservable.clear();
  55396. };
  55397. /**
  55398. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55399. * @param radius The radius of the sphere to emit from
  55400. * @returns the emitter
  55401. */
  55402. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55403. if (radius === void 0) { radius = 1; }
  55404. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55405. this.particleEmitterType = particleEmitter;
  55406. return particleEmitter;
  55407. };
  55408. /**
  55409. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55410. * @param radius The radius of the sphere to emit from
  55411. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55412. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55413. * @returns the emitter
  55414. */
  55415. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55416. if (radius === void 0) { radius = 1; }
  55417. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55418. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55419. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55420. this.particleEmitterType = particleEmitter;
  55421. return particleEmitter;
  55422. };
  55423. /**
  55424. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55425. * @param radius The radius of the cone to emit from
  55426. * @param angle The base angle of the cone
  55427. * @returns the emitter
  55428. */
  55429. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55430. if (radius === void 0) { radius = 1; }
  55431. if (angle === void 0) { angle = Math.PI / 4; }
  55432. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55433. this.particleEmitterType = particleEmitter;
  55434. return particleEmitter;
  55435. };
  55436. // 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.
  55437. /**
  55438. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55439. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55440. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55441. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55442. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55443. * @returns the emitter
  55444. */
  55445. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55446. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55447. this.particleEmitterType = particleEmitter;
  55448. this.direction1 = direction1;
  55449. this.direction2 = direction2;
  55450. this.minEmitBox = minEmitBox;
  55451. this.maxEmitBox = maxEmitBox;
  55452. return particleEmitter;
  55453. };
  55454. // Clone
  55455. /**
  55456. * Clones the particle system.
  55457. * @param name The name of the cloned object
  55458. * @param newEmitter The new emitter to use
  55459. * @returns the cloned particle system
  55460. */
  55461. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55462. var custom = null;
  55463. var program = null;
  55464. if (this.customShader != null) {
  55465. program = this.customShader;
  55466. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55467. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55468. }
  55469. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55470. result.customShader = program;
  55471. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55472. if (newEmitter === undefined) {
  55473. newEmitter = this.emitter;
  55474. }
  55475. result.emitter = newEmitter;
  55476. if (this.particleTexture) {
  55477. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55478. }
  55479. if (!this.preventAutoStart) {
  55480. result.start();
  55481. }
  55482. return result;
  55483. };
  55484. /**
  55485. * Serializes the particle system to a JSON object.
  55486. * @returns the JSON object
  55487. */
  55488. ParticleSystem.prototype.serialize = function () {
  55489. var serializationObject = {};
  55490. serializationObject.name = this.name;
  55491. serializationObject.id = this.id;
  55492. // Emitter
  55493. if (this.emitter.position) {
  55494. var emitterMesh = this.emitter;
  55495. serializationObject.emitterId = emitterMesh.id;
  55496. }
  55497. else {
  55498. var emitterPosition = this.emitter;
  55499. serializationObject.emitter = emitterPosition.asArray();
  55500. }
  55501. serializationObject.capacity = this.getCapacity();
  55502. if (this.particleTexture) {
  55503. serializationObject.textureName = this.particleTexture.name;
  55504. }
  55505. // Animations
  55506. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55507. // Particle system
  55508. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55509. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55510. serializationObject.minSize = this.minSize;
  55511. serializationObject.maxSize = this.maxSize;
  55512. serializationObject.minEmitPower = this.minEmitPower;
  55513. serializationObject.maxEmitPower = this.maxEmitPower;
  55514. serializationObject.minLifeTime = this.minLifeTime;
  55515. serializationObject.maxLifeTime = this.maxLifeTime;
  55516. serializationObject.emitRate = this.emitRate;
  55517. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55518. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55519. serializationObject.gravity = this.gravity.asArray();
  55520. serializationObject.direction1 = this.direction1.asArray();
  55521. serializationObject.direction2 = this.direction2.asArray();
  55522. serializationObject.color1 = this.color1.asArray();
  55523. serializationObject.color2 = this.color2.asArray();
  55524. serializationObject.colorDead = this.colorDead.asArray();
  55525. serializationObject.updateSpeed = this.updateSpeed;
  55526. serializationObject.targetStopDuration = this.targetStopDuration;
  55527. serializationObject.textureMask = this.textureMask.asArray();
  55528. serializationObject.blendMode = this.blendMode;
  55529. serializationObject.customShader = this.customShader;
  55530. serializationObject.preventAutoStart = this.preventAutoStart;
  55531. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55532. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55533. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55534. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55535. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55536. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55537. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55538. // Emitter
  55539. if (this.particleEmitterType) {
  55540. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55541. }
  55542. return serializationObject;
  55543. };
  55544. /**
  55545. * Parses a JSON object to create a particle system.
  55546. * @param parsedParticleSystem The JSON object to parse
  55547. * @param scene The scene to create the particle system in
  55548. * @param rootUrl The root url to use to load external dependencies like texture
  55549. * @returns the Parsed particle system
  55550. */
  55551. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55552. var name = parsedParticleSystem.name;
  55553. var custom = null;
  55554. var program = null;
  55555. if (parsedParticleSystem.customShader) {
  55556. program = parsedParticleSystem.customShader;
  55557. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55558. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55559. }
  55560. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55561. particleSystem.customShader = program;
  55562. if (parsedParticleSystem.id) {
  55563. particleSystem.id = parsedParticleSystem.id;
  55564. }
  55565. // Auto start
  55566. if (parsedParticleSystem.preventAutoStart) {
  55567. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55568. }
  55569. // Texture
  55570. if (parsedParticleSystem.textureName) {
  55571. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55572. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55573. }
  55574. // Emitter
  55575. if (parsedParticleSystem.emitterId) {
  55576. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55577. }
  55578. else {
  55579. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55580. }
  55581. // Animations
  55582. if (parsedParticleSystem.animations) {
  55583. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55584. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55585. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55586. }
  55587. }
  55588. if (parsedParticleSystem.autoAnimate) {
  55589. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55590. }
  55591. // Particle system
  55592. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55593. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55594. particleSystem.minSize = parsedParticleSystem.minSize;
  55595. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55596. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55597. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55598. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55599. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55600. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55601. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55602. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55603. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55604. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55605. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55606. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55607. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55608. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55609. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55610. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55611. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55612. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55613. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55614. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55615. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55616. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55617. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55618. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55619. if (!particleSystem.preventAutoStart) {
  55620. particleSystem.start();
  55621. }
  55622. return particleSystem;
  55623. };
  55624. /**
  55625. * Source color is added to the destination color without alpha affecting the result.
  55626. */
  55627. ParticleSystem.BLENDMODE_ONEONE = 0;
  55628. /**
  55629. * Blend current color and particle color using particle’s alpha.
  55630. */
  55631. ParticleSystem.BLENDMODE_STANDARD = 1;
  55632. return ParticleSystem;
  55633. }());
  55634. BABYLON.ParticleSystem = ParticleSystem;
  55635. })(BABYLON || (BABYLON = {}));
  55636. //# sourceMappingURL=babylon.particleSystem.js.map
  55637. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55638. var BABYLON;
  55639. (function (BABYLON) {
  55640. /**
  55641. * Particle emitter emitting particles from the inside of a box.
  55642. * It emits the particles randomly between 2 given directions.
  55643. */
  55644. var BoxParticleEmitter = /** @class */ (function () {
  55645. /**
  55646. * Creates a new instance BoxParticleEmitter
  55647. */
  55648. function BoxParticleEmitter() {
  55649. /**
  55650. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55651. */
  55652. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55653. /**
  55654. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55655. */
  55656. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55657. /**
  55658. * 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.
  55659. */
  55660. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55661. /**
  55662. * 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.
  55663. */
  55664. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55665. }
  55666. /**
  55667. * Called by the particle System when the direction is computed for the created particle.
  55668. * @param emitPower is the power of the particle (speed)
  55669. * @param worldMatrix is the world matrix of the particle system
  55670. * @param directionToUpdate is the direction vector to update with the result
  55671. * @param particle is the particle we are computed the direction for
  55672. */
  55673. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55674. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55675. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55676. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55677. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55678. };
  55679. /**
  55680. * Called by the particle System when the position is computed for the created particle.
  55681. * @param worldMatrix is the world matrix of the particle system
  55682. * @param positionToUpdate is the position vector to update with the result
  55683. * @param particle is the particle we are computed the position for
  55684. */
  55685. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55686. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55687. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55688. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55690. };
  55691. /**
  55692. * Clones the current emitter and returns a copy of it
  55693. * @returns the new emitter
  55694. */
  55695. BoxParticleEmitter.prototype.clone = function () {
  55696. var newOne = new BoxParticleEmitter();
  55697. BABYLON.Tools.DeepCopy(this, newOne);
  55698. return newOne;
  55699. };
  55700. /**
  55701. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55702. * @param effect defines the update shader
  55703. */
  55704. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55705. effect.setVector3("direction1", this.direction1);
  55706. effect.setVector3("direction2", this.direction2);
  55707. effect.setVector3("minEmitBox", this.minEmitBox);
  55708. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55709. };
  55710. /**
  55711. * Returns a string to use to update the GPU particles update shader
  55712. * @returns a string containng the defines string
  55713. */
  55714. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55715. return "#define BOXEMITTER";
  55716. };
  55717. /**
  55718. * Returns the string "BoxEmitter"
  55719. * @returns a string containing the class name
  55720. */
  55721. BoxParticleEmitter.prototype.getClassName = function () {
  55722. return "BoxEmitter";
  55723. };
  55724. /**
  55725. * Serializes the particle system to a JSON object.
  55726. * @returns the JSON object
  55727. */
  55728. BoxParticleEmitter.prototype.serialize = function () {
  55729. var serializationObject = {};
  55730. serializationObject.type = this.getClassName();
  55731. serializationObject.direction1 = this.direction1.asArray();
  55732. ;
  55733. serializationObject.direction2 = this.direction2.asArray();
  55734. ;
  55735. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55736. ;
  55737. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55738. ;
  55739. return serializationObject;
  55740. };
  55741. /**
  55742. * Parse properties from a JSON object
  55743. * @param serializationObject defines the JSON object
  55744. */
  55745. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55746. this.direction1.copyFrom(serializationObject.direction1);
  55747. this.direction2.copyFrom(serializationObject.direction2);
  55748. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55749. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55750. };
  55751. return BoxParticleEmitter;
  55752. }());
  55753. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55754. })(BABYLON || (BABYLON = {}));
  55755. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55756. var BABYLON;
  55757. (function (BABYLON) {
  55758. /**
  55759. * Particle emitter emitting particles from the inside of a cone.
  55760. * It emits the particles alongside the cone volume from the base to the particle.
  55761. * The emission direction might be randomized.
  55762. */
  55763. var ConeParticleEmitter = /** @class */ (function () {
  55764. /**
  55765. * Creates a new instance ConeParticleEmitter
  55766. * @param radius the radius of the emission cone (1 by default)
  55767. * @param angles the cone base angle (PI by default)
  55768. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55769. */
  55770. function ConeParticleEmitter(radius,
  55771. /**
  55772. * The radius of the emission cone.
  55773. */
  55774. angle,
  55775. /**
  55776. * The cone base angle.
  55777. */
  55778. directionRandomizer) {
  55779. if (radius === void 0) { radius = 1; }
  55780. if (angle === void 0) { angle = Math.PI; }
  55781. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55782. this.angle = angle;
  55783. this.directionRandomizer = directionRandomizer;
  55784. this.radius = radius;
  55785. }
  55786. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55787. /**
  55788. * Gets the radius of the emission cone.
  55789. */
  55790. get: function () {
  55791. return this._radius;
  55792. },
  55793. /**
  55794. * Sets the radius of the emission cone.
  55795. */
  55796. set: function (value) {
  55797. this._radius = value;
  55798. if (this.angle !== 0) {
  55799. this._height = value / Math.tan(this.angle / 2);
  55800. }
  55801. else {
  55802. this._height = 1;
  55803. }
  55804. },
  55805. enumerable: true,
  55806. configurable: true
  55807. });
  55808. /**
  55809. * Called by the particle System when the direction is computed for the created particle.
  55810. * @param emitPower is the power of the particle (speed)
  55811. * @param worldMatrix is the world matrix of the particle system
  55812. * @param directionToUpdate is the direction vector to update with the result
  55813. * @param particle is the particle we are computed the direction for
  55814. */
  55815. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55816. if (this.angle === 0) {
  55817. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55818. }
  55819. else {
  55820. // measure the direction Vector from the emitter to the particle.
  55821. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55822. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55823. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55824. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55825. direction.x += randX;
  55826. direction.y += randY;
  55827. direction.z += randZ;
  55828. direction.normalize();
  55829. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55830. }
  55831. };
  55832. /**
  55833. * Called by the particle System when the position is computed for the created particle.
  55834. * @param worldMatrix is the world matrix of the particle system
  55835. * @param positionToUpdate is the position vector to update with the result
  55836. * @param particle is the particle we are computed the position for
  55837. */
  55838. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55839. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55840. var h = BABYLON.Scalar.RandomRange(0, 1);
  55841. // Better distribution in a cone at normal angles.
  55842. h = 1 - h * h;
  55843. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55844. radius = radius * h;
  55845. var randX = radius * Math.sin(s);
  55846. var randZ = radius * Math.cos(s);
  55847. var randY = h * this._height;
  55848. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55849. };
  55850. /**
  55851. * Clones the current emitter and returns a copy of it
  55852. * @returns the new emitter
  55853. */
  55854. ConeParticleEmitter.prototype.clone = function () {
  55855. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55856. BABYLON.Tools.DeepCopy(this, newOne);
  55857. return newOne;
  55858. };
  55859. /**
  55860. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55861. * @param effect defines the update shader
  55862. */
  55863. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55864. effect.setFloat("radius", this.radius);
  55865. effect.setFloat("angle", this.angle);
  55866. effect.setFloat("height", this._height);
  55867. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55868. };
  55869. /**
  55870. * Returns a string to use to update the GPU particles update shader
  55871. * @returns a string containng the defines string
  55872. */
  55873. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55874. return "#define CONEEMITTER";
  55875. };
  55876. /**
  55877. * Returns the string "BoxEmitter"
  55878. * @returns a string containing the class name
  55879. */
  55880. ConeParticleEmitter.prototype.getClassName = function () {
  55881. return "ConeEmitter";
  55882. };
  55883. /**
  55884. * Serializes the particle system to a JSON object.
  55885. * @returns the JSON object
  55886. */
  55887. ConeParticleEmitter.prototype.serialize = function () {
  55888. var serializationObject = {};
  55889. serializationObject.type = this.getClassName();
  55890. serializationObject.radius = this.radius;
  55891. serializationObject.angle = this.angle;
  55892. serializationObject.directionRandomizer = this.directionRandomizer;
  55893. return serializationObject;
  55894. };
  55895. /**
  55896. * Parse properties from a JSON object
  55897. * @param serializationObject defines the JSON object
  55898. */
  55899. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55900. this.radius = serializationObject.radius;
  55901. this.angle = serializationObject.angle;
  55902. this.directionRandomizer = serializationObject.directionRandomizer;
  55903. };
  55904. return ConeParticleEmitter;
  55905. }());
  55906. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55907. })(BABYLON || (BABYLON = {}));
  55908. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55909. var BABYLON;
  55910. (function (BABYLON) {
  55911. /**
  55912. * Particle emitter emitting particles from the inside of a sphere.
  55913. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55914. */
  55915. var SphereParticleEmitter = /** @class */ (function () {
  55916. /**
  55917. * Creates a new instance SphereParticleEmitter
  55918. * @param radius the radius of the emission sphere (1 by default)
  55919. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55920. */
  55921. function SphereParticleEmitter(
  55922. /**
  55923. * The radius of the emission sphere.
  55924. */
  55925. radius,
  55926. /**
  55927. * How much to randomize the particle direction [0-1].
  55928. */
  55929. directionRandomizer) {
  55930. if (radius === void 0) { radius = 1; }
  55931. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55932. this.radius = radius;
  55933. this.directionRandomizer = directionRandomizer;
  55934. }
  55935. /**
  55936. * Called by the particle System when the direction is computed for the created particle.
  55937. * @param emitPower is the power of the particle (speed)
  55938. * @param worldMatrix is the world matrix of the particle system
  55939. * @param directionToUpdate is the direction vector to update with the result
  55940. * @param particle is the particle we are computed the direction for
  55941. */
  55942. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55943. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55944. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55945. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55946. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55947. direction.x += randX;
  55948. direction.y += randY;
  55949. direction.z += randZ;
  55950. direction.normalize();
  55951. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55952. };
  55953. /**
  55954. * Called by the particle System when the position is computed for the created particle.
  55955. * @param worldMatrix is the world matrix of the particle system
  55956. * @param positionToUpdate is the position vector to update with the result
  55957. * @param particle is the particle we are computed the position for
  55958. */
  55959. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55960. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55961. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55962. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55963. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55964. var randY = randRadius * Math.cos(theta);
  55965. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55966. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55967. };
  55968. /**
  55969. * Clones the current emitter and returns a copy of it
  55970. * @returns the new emitter
  55971. */
  55972. SphereParticleEmitter.prototype.clone = function () {
  55973. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55974. BABYLON.Tools.DeepCopy(this, newOne);
  55975. return newOne;
  55976. };
  55977. /**
  55978. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55979. * @param effect defines the update shader
  55980. */
  55981. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55982. effect.setFloat("radius", this.radius);
  55983. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55984. };
  55985. /**
  55986. * Returns a string to use to update the GPU particles update shader
  55987. * @returns a string containng the defines string
  55988. */
  55989. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55990. return "#define SPHEREEMITTER";
  55991. };
  55992. /**
  55993. * Returns the string "SphereParticleEmitter"
  55994. * @returns a string containing the class name
  55995. */
  55996. SphereParticleEmitter.prototype.getClassName = function () {
  55997. return "SphereParticleEmitter";
  55998. };
  55999. /**
  56000. * Serializes the particle system to a JSON object.
  56001. * @returns the JSON object
  56002. */
  56003. SphereParticleEmitter.prototype.serialize = function () {
  56004. var serializationObject = {};
  56005. serializationObject.type = this.getClassName();
  56006. serializationObject.radius = this.radius;
  56007. serializationObject.directionRandomizer = this.directionRandomizer;
  56008. return serializationObject;
  56009. };
  56010. /**
  56011. * Parse properties from a JSON object
  56012. * @param serializationObject defines the JSON object
  56013. */
  56014. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56015. this.radius = serializationObject.radius;
  56016. this.directionRandomizer = serializationObject.directionRandomizer;
  56017. };
  56018. return SphereParticleEmitter;
  56019. }());
  56020. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56021. /**
  56022. * Particle emitter emitting particles from the inside of a sphere.
  56023. * It emits the particles randomly between two vectors.
  56024. */
  56025. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56026. __extends(SphereDirectedParticleEmitter, _super);
  56027. /**
  56028. * Creates a new instance SphereDirectedParticleEmitter
  56029. * @param radius the radius of the emission sphere (1 by default)
  56030. * @param direction1 the min limit of the emission direction (up vector by default)
  56031. * @param direction2 the max limit of the emission direction (up vector by default)
  56032. */
  56033. function SphereDirectedParticleEmitter(radius,
  56034. /**
  56035. * The min limit of the emission direction.
  56036. */
  56037. direction1,
  56038. /**
  56039. * The max limit of the emission direction.
  56040. */
  56041. direction2) {
  56042. if (radius === void 0) { radius = 1; }
  56043. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56044. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56045. var _this = _super.call(this, radius) || this;
  56046. _this.direction1 = direction1;
  56047. _this.direction2 = direction2;
  56048. return _this;
  56049. }
  56050. /**
  56051. * Called by the particle System when the direction is computed for the created particle.
  56052. * @param emitPower is the power of the particle (speed)
  56053. * @param worldMatrix is the world matrix of the particle system
  56054. * @param directionToUpdate is the direction vector to update with the result
  56055. * @param particle is the particle we are computed the direction for
  56056. */
  56057. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56058. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56059. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56060. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56061. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56062. };
  56063. /**
  56064. * Clones the current emitter and returns a copy of it
  56065. * @returns the new emitter
  56066. */
  56067. SphereDirectedParticleEmitter.prototype.clone = function () {
  56068. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56069. BABYLON.Tools.DeepCopy(this, newOne);
  56070. return newOne;
  56071. };
  56072. /**
  56073. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56074. * @param effect defines the update shader
  56075. */
  56076. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56077. effect.setFloat("radius", this.radius);
  56078. effect.setVector3("direction1", this.direction1);
  56079. effect.setVector3("direction2", this.direction2);
  56080. };
  56081. /**
  56082. * Returns a string to use to update the GPU particles update shader
  56083. * @returns a string containng the defines string
  56084. */
  56085. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56086. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56087. };
  56088. /**
  56089. * Returns the string "SphereDirectedParticleEmitter"
  56090. * @returns a string containing the class name
  56091. */
  56092. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56093. return "SphereDirectedParticleEmitter";
  56094. };
  56095. /**
  56096. * Serializes the particle system to a JSON object.
  56097. * @returns the JSON object
  56098. */
  56099. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56100. var serializationObject = _super.prototype.serialize.call(this);
  56101. ;
  56102. serializationObject.direction1 = this.direction1.asArray();
  56103. ;
  56104. serializationObject.direction2 = this.direction2.asArray();
  56105. ;
  56106. return serializationObject;
  56107. };
  56108. /**
  56109. * Parse properties from a JSON object
  56110. * @param serializationObject defines the JSON object
  56111. */
  56112. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56113. _super.prototype.parse.call(this, serializationObject);
  56114. this.direction1.copyFrom(serializationObject.direction1);
  56115. this.direction2.copyFrom(serializationObject.direction2);
  56116. };
  56117. return SphereDirectedParticleEmitter;
  56118. }(SphereParticleEmitter));
  56119. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56120. })(BABYLON || (BABYLON = {}));
  56121. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56122. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56123. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56124. s = arguments[i];
  56125. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56126. t[p] = s[p];
  56127. }
  56128. return t;
  56129. };
  56130. var BABYLON;
  56131. (function (BABYLON) {
  56132. /**
  56133. * This represents a GPU particle system in Babylon
  56134. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56135. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56136. */
  56137. var GPUParticleSystem = /** @class */ (function () {
  56138. /**
  56139. * Instantiates a GPU particle system.
  56140. * 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.
  56141. * @param name The name of the particle system
  56142. * @param capacity The max number of particles alive at the same time
  56143. * @param scene The scene the particle system belongs to
  56144. */
  56145. function GPUParticleSystem(name, options, scene) {
  56146. /**
  56147. * The emitter represents the Mesh or position we are attaching the particle system to.
  56148. */
  56149. this.emitter = null;
  56150. /**
  56151. * The rendering group used by the Particle system to chose when to render.
  56152. */
  56153. this.renderingGroupId = 0;
  56154. /**
  56155. * The layer mask we are rendering the particles through.
  56156. */
  56157. this.layerMask = 0x0FFFFFFF;
  56158. this._targetIndex = 0;
  56159. this._currentRenderId = -1;
  56160. this._started = false;
  56161. this._stopped = false;
  56162. this._timeDelta = 0;
  56163. this._attributesStrideSize = 14;
  56164. this._actualFrame = 0;
  56165. /**
  56166. * List of animations used by the particle system.
  56167. */
  56168. this.animations = [];
  56169. /**
  56170. * An event triggered when the system is disposed.
  56171. */
  56172. this.onDisposeObservable = new BABYLON.Observable();
  56173. /**
  56174. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56175. */
  56176. this.updateSpeed = 0.01;
  56177. /**
  56178. * The amount of time the particle system is running (depends of the overall update speed).
  56179. */
  56180. this.targetStopDuration = 0;
  56181. /**
  56182. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56183. */
  56184. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56185. /**
  56186. * Minimum life time of emitting particles.
  56187. */
  56188. this.minLifeTime = 1;
  56189. /**
  56190. * Maximum life time of emitting particles.
  56191. */
  56192. this.maxLifeTime = 1;
  56193. /**
  56194. * Minimum Size of emitting particles.
  56195. */
  56196. this.minSize = 1;
  56197. /**
  56198. * Maximum Size of emitting particles.
  56199. */
  56200. this.maxSize = 1;
  56201. /**
  56202. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56203. */
  56204. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56205. /**
  56206. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56207. */
  56208. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56209. /**
  56210. * Color the particle will have at the end of its lifetime.
  56211. */
  56212. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56213. /**
  56214. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56215. */
  56216. this.emitRate = 100;
  56217. /**
  56218. * You can use gravity if you want to give an orientation to your particles.
  56219. */
  56220. this.gravity = BABYLON.Vector3.Zero();
  56221. /**
  56222. * Minimum power of emitting particles.
  56223. */
  56224. this.minEmitPower = 1;
  56225. /**
  56226. * Maximum power of emitting particles.
  56227. */
  56228. this.maxEmitPower = 1;
  56229. /**
  56230. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56231. * to override the particles.
  56232. */
  56233. this.forceDepthWrite = false;
  56234. this.id = name;
  56235. this.name = name;
  56236. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56237. this._engine = this._scene.getEngine();
  56238. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56239. this._capacity = fullOptions.capacity;
  56240. this._activeCount = fullOptions.capacity;
  56241. this._currentActiveCount = 0;
  56242. this._scene.particleSystems.push(this);
  56243. this._updateEffectOptions = {
  56244. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56245. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56246. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56247. uniformBuffersNames: [],
  56248. samplers: ["randomSampler"],
  56249. defines: "",
  56250. fallbacks: null,
  56251. onCompiled: null,
  56252. onError: null,
  56253. indexParameters: null,
  56254. maxSimultaneousLights: 0,
  56255. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56256. };
  56257. // Random data
  56258. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56259. var d = [];
  56260. for (var i = 0; i < maxTextureSize; ++i) {
  56261. d.push(Math.random());
  56262. d.push(Math.random());
  56263. d.push(Math.random());
  56264. d.push(Math.random());
  56265. }
  56266. 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);
  56267. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56268. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56269. this._randomTextureSize = maxTextureSize;
  56270. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56271. }
  56272. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56273. /**
  56274. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56275. */
  56276. get: function () {
  56277. if (!BABYLON.Engine.LastCreatedEngine) {
  56278. return false;
  56279. }
  56280. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56281. },
  56282. enumerable: true,
  56283. configurable: true
  56284. });
  56285. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56286. /**
  56287. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56288. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56289. */
  56290. get: function () {
  56291. if (this.particleEmitterType.direction1) {
  56292. return this.particleEmitterType.direction1;
  56293. }
  56294. return BABYLON.Vector3.Zero();
  56295. },
  56296. set: function (value) {
  56297. if (this.particleEmitterType.direction1) {
  56298. this.particleEmitterType.direction1 = value;
  56299. }
  56300. },
  56301. enumerable: true,
  56302. configurable: true
  56303. });
  56304. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56305. /**
  56306. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56307. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56308. */
  56309. get: function () {
  56310. if (this.particleEmitterType.direction2) {
  56311. return this.particleEmitterType.direction2;
  56312. }
  56313. return BABYLON.Vector3.Zero();
  56314. },
  56315. set: function (value) {
  56316. if (this.particleEmitterType.direction2) {
  56317. this.particleEmitterType.direction2 = value;
  56318. }
  56319. },
  56320. enumerable: true,
  56321. configurable: true
  56322. });
  56323. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56324. /**
  56325. * 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.
  56326. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56327. */
  56328. get: function () {
  56329. if (this.particleEmitterType.minEmitBox) {
  56330. return this.particleEmitterType.minEmitBox;
  56331. }
  56332. return BABYLON.Vector3.Zero();
  56333. },
  56334. set: function (value) {
  56335. if (this.particleEmitterType.minEmitBox) {
  56336. this.particleEmitterType.minEmitBox = value;
  56337. }
  56338. },
  56339. enumerable: true,
  56340. configurable: true
  56341. });
  56342. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56343. /**
  56344. * 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.
  56345. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56346. */
  56347. get: function () {
  56348. if (this.particleEmitterType.maxEmitBox) {
  56349. return this.particleEmitterType.maxEmitBox;
  56350. }
  56351. return BABYLON.Vector3.Zero();
  56352. },
  56353. set: function (value) {
  56354. if (this.particleEmitterType.maxEmitBox) {
  56355. this.particleEmitterType.maxEmitBox = value;
  56356. }
  56357. },
  56358. enumerable: true,
  56359. configurable: true
  56360. });
  56361. /**
  56362. * Gets the maximum number of particles active at the same time.
  56363. * @returns The max number of active particles.
  56364. */
  56365. GPUParticleSystem.prototype.getCapacity = function () {
  56366. return this._capacity;
  56367. };
  56368. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56369. /**
  56370. * Gets or set the number of active particles
  56371. */
  56372. get: function () {
  56373. return this._activeCount;
  56374. },
  56375. set: function (value) {
  56376. this._activeCount = Math.min(value, this._capacity);
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. /**
  56382. * Is this system ready to be used/rendered
  56383. * @return true if the system is ready
  56384. */
  56385. GPUParticleSystem.prototype.isReady = function () {
  56386. if (!this._updateEffect) {
  56387. this._recreateUpdateEffect();
  56388. this._recreateRenderEffect();
  56389. return false;
  56390. }
  56391. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56392. return false;
  56393. }
  56394. return true;
  56395. };
  56396. /**
  56397. * Gets Wether the system has been started.
  56398. * @returns True if it has been started, otherwise false.
  56399. */
  56400. GPUParticleSystem.prototype.isStarted = function () {
  56401. return this._started;
  56402. };
  56403. /**
  56404. * Starts the particle system and begins to emit.
  56405. */
  56406. GPUParticleSystem.prototype.start = function () {
  56407. this._started = true;
  56408. this._stopped = false;
  56409. };
  56410. /**
  56411. * Stops the particle system.
  56412. */
  56413. GPUParticleSystem.prototype.stop = function () {
  56414. this._stopped = true;
  56415. };
  56416. /**
  56417. * Remove all active particles
  56418. */
  56419. GPUParticleSystem.prototype.reset = function () {
  56420. this._releaseBuffers();
  56421. this._releaseVAOs();
  56422. this._currentActiveCount = 0;
  56423. this._targetIndex = 0;
  56424. };
  56425. /**
  56426. * Returns the string "GPUParticleSystem"
  56427. * @returns a string containing the class name
  56428. */
  56429. GPUParticleSystem.prototype.getClassName = function () {
  56430. return "GPUParticleSystem";
  56431. };
  56432. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56433. var updateVertexBuffers = {};
  56434. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56435. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56436. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56437. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56438. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56439. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56440. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56441. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56442. this._engine.bindArrayBuffer(null);
  56443. return vao;
  56444. };
  56445. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56446. var renderVertexBuffers = {};
  56447. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56448. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56449. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56450. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56451. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56452. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56453. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56454. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56455. this._engine.bindArrayBuffer(null);
  56456. return vao;
  56457. };
  56458. GPUParticleSystem.prototype._initialize = function (force) {
  56459. if (force === void 0) { force = false; }
  56460. if (this._buffer0 && !force) {
  56461. return;
  56462. }
  56463. var engine = this._scene.getEngine();
  56464. var data = new Array();
  56465. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56466. // position
  56467. data.push(0.0);
  56468. data.push(0.0);
  56469. data.push(0.0);
  56470. // Age and life
  56471. data.push(0.0); // create the particle as a dead one to create a new one at start
  56472. data.push(0.0);
  56473. // Seed
  56474. data.push(Math.random());
  56475. // Size
  56476. data.push(0.0);
  56477. // color
  56478. data.push(0.0);
  56479. data.push(0.0);
  56480. data.push(0.0);
  56481. data.push(0.0);
  56482. // direction
  56483. data.push(0.0);
  56484. data.push(0.0);
  56485. data.push(0.0);
  56486. }
  56487. // Sprite data
  56488. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56489. -0.5, 0.5, 0, 1,
  56490. -0.5, -0.5, 0, 0,
  56491. 0.5, -0.5, 1, 0]);
  56492. // Buffers
  56493. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56494. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56495. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56496. // Update VAO
  56497. this._updateVAO = [];
  56498. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56499. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56500. // Render VAO
  56501. this._renderVAO = [];
  56502. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56503. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56504. // Links
  56505. this._sourceBuffer = this._buffer0;
  56506. this._targetBuffer = this._buffer1;
  56507. };
  56508. /** @ignore */
  56509. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56510. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56511. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56512. return;
  56513. }
  56514. this._updateEffectOptions.defines = defines;
  56515. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56516. };
  56517. /** @ignore */
  56518. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56519. var defines = "";
  56520. if (this._scene.clipPlane) {
  56521. defines = "\n#define CLIPPLANE";
  56522. }
  56523. if (this._renderEffect && this._renderEffect.defines === defines) {
  56524. return;
  56525. }
  56526. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56527. };
  56528. /**
  56529. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56530. */
  56531. GPUParticleSystem.prototype.animate = function () {
  56532. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56533. this._actualFrame += this._timeDelta;
  56534. if (!this._stopped) {
  56535. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56536. this.stop();
  56537. }
  56538. }
  56539. };
  56540. /**
  56541. * Renders the particle system in its current state.
  56542. * @returns the current number of particles
  56543. */
  56544. GPUParticleSystem.prototype.render = function () {
  56545. if (!this._started) {
  56546. return 0;
  56547. }
  56548. this._recreateUpdateEffect();
  56549. this._recreateRenderEffect();
  56550. if (!this.isReady()) {
  56551. return 0;
  56552. }
  56553. if (this._currentRenderId === this._scene.getRenderId()) {
  56554. return 0;
  56555. }
  56556. this._currentRenderId = this._scene.getRenderId();
  56557. // Get everything ready to render
  56558. this._initialize();
  56559. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56560. // Enable update effect
  56561. this._engine.enableEffect(this._updateEffect);
  56562. this._engine.setState(false);
  56563. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56564. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56565. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56566. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56567. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56568. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56569. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56570. this._updateEffect.setDirectColor4("color1", this.color1);
  56571. this._updateEffect.setDirectColor4("color2", this.color2);
  56572. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56573. this._updateEffect.setVector3("gravity", this.gravity);
  56574. if (this.particleEmitterType) {
  56575. this.particleEmitterType.applyToShader(this._updateEffect);
  56576. }
  56577. var emitterWM;
  56578. if (this.emitter.position) {
  56579. var emitterMesh = this.emitter;
  56580. emitterWM = emitterMesh.getWorldMatrix();
  56581. }
  56582. else {
  56583. var emitterPosition = this.emitter;
  56584. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56585. }
  56586. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56587. // Bind source VAO
  56588. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56589. // Update
  56590. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56591. this._engine.setRasterizerState(false);
  56592. this._engine.beginTransformFeedback();
  56593. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56594. this._engine.endTransformFeedback();
  56595. this._engine.setRasterizerState(true);
  56596. this._engine.bindTransformFeedbackBuffer(null);
  56597. // Enable render effect
  56598. this._engine.enableEffect(this._renderEffect);
  56599. var viewMatrix = this._scene.getViewMatrix();
  56600. this._renderEffect.setMatrix("view", viewMatrix);
  56601. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56602. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56603. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56604. if (this._scene.clipPlane) {
  56605. var clipPlane = this._scene.clipPlane;
  56606. var invView = viewMatrix.clone();
  56607. invView.invert();
  56608. this._renderEffect.setMatrix("invView", invView);
  56609. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56610. }
  56611. // Draw order
  56612. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56613. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56614. }
  56615. else {
  56616. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56617. }
  56618. if (this.forceDepthWrite) {
  56619. this._engine.setDepthWrite(true);
  56620. }
  56621. // Bind source VAO
  56622. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56623. // Render
  56624. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56625. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56626. // Switch VAOs
  56627. this._targetIndex++;
  56628. if (this._targetIndex === 2) {
  56629. this._targetIndex = 0;
  56630. }
  56631. // Switch buffers
  56632. var tmpBuffer = this._sourceBuffer;
  56633. this._sourceBuffer = this._targetBuffer;
  56634. this._targetBuffer = tmpBuffer;
  56635. return this._currentActiveCount;
  56636. };
  56637. /**
  56638. * Rebuilds the particle system
  56639. */
  56640. GPUParticleSystem.prototype.rebuild = function () {
  56641. this._initialize(true);
  56642. };
  56643. GPUParticleSystem.prototype._releaseBuffers = function () {
  56644. if (this._buffer0) {
  56645. this._buffer0.dispose();
  56646. this._buffer0 = null;
  56647. }
  56648. if (this._buffer1) {
  56649. this._buffer1.dispose();
  56650. this._buffer1 = null;
  56651. }
  56652. if (this._spriteBuffer) {
  56653. this._spriteBuffer.dispose();
  56654. this._spriteBuffer = null;
  56655. }
  56656. };
  56657. GPUParticleSystem.prototype._releaseVAOs = function () {
  56658. if (!this._updateVAO) {
  56659. return;
  56660. }
  56661. for (var index = 0; index < this._updateVAO.length; index++) {
  56662. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56663. }
  56664. this._updateVAO = [];
  56665. for (var index = 0; index < this._renderVAO.length; index++) {
  56666. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56667. }
  56668. this._renderVAO = [];
  56669. };
  56670. /**
  56671. * Disposes the particle system and free the associated resources
  56672. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56673. */
  56674. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56675. if (disposeTexture === void 0) { disposeTexture = true; }
  56676. var index = this._scene.particleSystems.indexOf(this);
  56677. if (index > -1) {
  56678. this._scene.particleSystems.splice(index, 1);
  56679. }
  56680. this._releaseBuffers();
  56681. this._releaseVAOs();
  56682. if (this._randomTexture) {
  56683. this._randomTexture.dispose();
  56684. this._randomTexture = null;
  56685. }
  56686. if (disposeTexture && this.particleTexture) {
  56687. this.particleTexture.dispose();
  56688. this.particleTexture = null;
  56689. }
  56690. // Callback
  56691. this.onDisposeObservable.notifyObservers(this);
  56692. this.onDisposeObservable.clear();
  56693. };
  56694. /**
  56695. * Clones the particle system.
  56696. * @param name The name of the cloned object
  56697. * @param newEmitter The new emitter to use
  56698. * @returns the cloned particle system
  56699. */
  56700. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56701. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56702. BABYLON.Tools.DeepCopy(this, result);
  56703. if (newEmitter === undefined) {
  56704. newEmitter = this.emitter;
  56705. }
  56706. result.emitter = newEmitter;
  56707. if (this.particleTexture) {
  56708. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56709. }
  56710. return result;
  56711. };
  56712. /**
  56713. * Serializes the particle system to a JSON object.
  56714. * @returns the JSON object
  56715. */
  56716. GPUParticleSystem.prototype.serialize = function () {
  56717. var serializationObject = {};
  56718. serializationObject.name = this.name;
  56719. serializationObject.id = this.id;
  56720. // Emitter
  56721. if (this.emitter.position) {
  56722. var emitterMesh = this.emitter;
  56723. serializationObject.emitterId = emitterMesh.id;
  56724. }
  56725. else {
  56726. var emitterPosition = this.emitter;
  56727. serializationObject.emitter = emitterPosition.asArray();
  56728. }
  56729. serializationObject.capacity = this.getCapacity();
  56730. if (this.particleTexture) {
  56731. serializationObject.textureName = this.particleTexture.name;
  56732. }
  56733. // Animations
  56734. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56735. // Particle system
  56736. serializationObject.activeParticleCount = this.activeParticleCount;
  56737. serializationObject.randomTextureSize = this._randomTextureSize;
  56738. serializationObject.minSize = this.minSize;
  56739. serializationObject.maxSize = this.maxSize;
  56740. serializationObject.minEmitPower = this.minEmitPower;
  56741. serializationObject.maxEmitPower = this.maxEmitPower;
  56742. serializationObject.minLifeTime = this.minLifeTime;
  56743. serializationObject.maxLifeTime = this.maxLifeTime;
  56744. serializationObject.emitRate = this.emitRate;
  56745. serializationObject.gravity = this.gravity.asArray();
  56746. serializationObject.color1 = this.color1.asArray();
  56747. serializationObject.color2 = this.color2.asArray();
  56748. serializationObject.colorDead = this.colorDead.asArray();
  56749. serializationObject.updateSpeed = this.updateSpeed;
  56750. serializationObject.targetStopDuration = this.targetStopDuration;
  56751. serializationObject.blendMode = this.blendMode;
  56752. // Emitter
  56753. if (this.particleEmitterType) {
  56754. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56755. }
  56756. return serializationObject;
  56757. };
  56758. /**
  56759. * Parses a JSON object to create a GPU particle system.
  56760. * @param parsedParticleSystem The JSON object to parse
  56761. * @param scene The scene to create the particle system in
  56762. * @param rootUrl The root url to use to load external dependencies like texture
  56763. * @returns the parsed GPU particle system
  56764. */
  56765. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56766. var name = parsedParticleSystem.name;
  56767. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56768. if (parsedParticleSystem.id) {
  56769. particleSystem.id = parsedParticleSystem.id;
  56770. }
  56771. // Texture
  56772. if (parsedParticleSystem.textureName) {
  56773. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56774. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56775. }
  56776. // Emitter
  56777. if (parsedParticleSystem.emitterId) {
  56778. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56779. }
  56780. else {
  56781. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56782. }
  56783. // Animations
  56784. if (parsedParticleSystem.animations) {
  56785. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56786. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56787. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56788. }
  56789. }
  56790. // Particle system
  56791. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56792. particleSystem.minSize = parsedParticleSystem.minSize;
  56793. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56794. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56795. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56796. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56797. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56798. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56799. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56800. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56801. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56802. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56803. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56804. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56805. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56806. // Emitter
  56807. if (parsedParticleSystem.particleEmitterType) {
  56808. var emitterType = void 0;
  56809. switch (parsedParticleSystem.particleEmitterType.type) {
  56810. case "SphereEmitter":
  56811. emitterType = new BABYLON.SphereParticleEmitter();
  56812. break;
  56813. case "SphereDirectedParticleEmitter":
  56814. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56815. break;
  56816. case "ConeEmitter":
  56817. emitterType = new BABYLON.ConeParticleEmitter();
  56818. break;
  56819. case "BoxEmitter":
  56820. default:
  56821. emitterType = new BABYLON.BoxParticleEmitter();
  56822. break;
  56823. }
  56824. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56825. particleSystem.particleEmitterType = emitterType;
  56826. }
  56827. return particleSystem;
  56828. };
  56829. return GPUParticleSystem;
  56830. }());
  56831. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56832. })(BABYLON || (BABYLON = {}));
  56833. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56834. var BABYLON;
  56835. (function (BABYLON) {
  56836. /**
  56837. * Represents one particle of a solid particle system.
  56838. */
  56839. var SolidParticle = /** @class */ (function () {
  56840. /**
  56841. * Creates a Solid Particle object.
  56842. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56843. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56844. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56845. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56846. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56847. * @param shapeId (integer) is the model shape identifier in the SPS.
  56848. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56849. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56850. */
  56851. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56852. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56853. /**
  56854. * particle global index
  56855. */
  56856. this.idx = 0;
  56857. /**
  56858. * The color of the particle
  56859. */
  56860. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56861. /**
  56862. * The world space position of the particle.
  56863. */
  56864. this.position = BABYLON.Vector3.Zero();
  56865. /**
  56866. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56867. */
  56868. this.rotation = BABYLON.Vector3.Zero();
  56869. /**
  56870. * The scaling of the particle.
  56871. */
  56872. this.scaling = BABYLON.Vector3.One();
  56873. /**
  56874. * The uvs of the particle.
  56875. */
  56876. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56877. /**
  56878. * The current speed of the particle.
  56879. */
  56880. this.velocity = BABYLON.Vector3.Zero();
  56881. /**
  56882. * The pivot point in the particle local space.
  56883. */
  56884. this.pivot = BABYLON.Vector3.Zero();
  56885. /**
  56886. * Must the particle be translated from its pivot point in its local space ?
  56887. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56888. * Default : false
  56889. */
  56890. this.translateFromPivot = false;
  56891. /**
  56892. * Is the particle active or not ?
  56893. */
  56894. this.alive = true;
  56895. /**
  56896. * Is the particle visible or not ?
  56897. */
  56898. this.isVisible = true;
  56899. /**
  56900. * Index of this particle in the global "positions" array (Internal use)
  56901. */
  56902. this._pos = 0;
  56903. /**
  56904. * Index of this particle in the global "indices" array (Internal use)
  56905. */
  56906. this._ind = 0;
  56907. /**
  56908. * ModelShape id of this particle
  56909. */
  56910. this.shapeId = 0;
  56911. /**
  56912. * Index of the particle in its shape id (Internal use)
  56913. */
  56914. this.idxInShape = 0;
  56915. /**
  56916. * Still set as invisible in order to skip useless computations (Internal use)
  56917. */
  56918. this._stillInvisible = false;
  56919. /**
  56920. * Last computed particle rotation matrix
  56921. */
  56922. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56923. /**
  56924. * Parent particle Id, if any.
  56925. * Default null.
  56926. */
  56927. this.parentId = null;
  56928. /**
  56929. * Internal global position in the SPS.
  56930. */
  56931. this._globalPosition = BABYLON.Vector3.Zero();
  56932. this.idx = particleIndex;
  56933. this._pos = positionIndex;
  56934. this._ind = indiceIndex;
  56935. this._model = model;
  56936. this.shapeId = shapeId;
  56937. this.idxInShape = idxInShape;
  56938. this._sps = sps;
  56939. if (modelBoundingInfo) {
  56940. this._modelBoundingInfo = modelBoundingInfo;
  56941. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56942. }
  56943. }
  56944. Object.defineProperty(SolidParticle.prototype, "scale", {
  56945. /**
  56946. * Legacy support, changed scale to scaling
  56947. */
  56948. get: function () {
  56949. return this.scaling;
  56950. },
  56951. /**
  56952. * Legacy support, changed scale to scaling
  56953. */
  56954. set: function (scale) {
  56955. this.scaling = scale;
  56956. },
  56957. enumerable: true,
  56958. configurable: true
  56959. });
  56960. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56961. /**
  56962. * Legacy support, changed quaternion to rotationQuaternion
  56963. */
  56964. get: function () {
  56965. return this.rotationQuaternion;
  56966. },
  56967. /**
  56968. * Legacy support, changed quaternion to rotationQuaternion
  56969. */
  56970. set: function (q) {
  56971. this.rotationQuaternion = q;
  56972. },
  56973. enumerable: true,
  56974. configurable: true
  56975. });
  56976. /**
  56977. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56978. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56979. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56980. * @returns true if it intersects
  56981. */
  56982. SolidParticle.prototype.intersectsMesh = function (target) {
  56983. if (!this._boundingInfo || !target._boundingInfo) {
  56984. return false;
  56985. }
  56986. if (this._sps._bSphereOnly) {
  56987. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56988. }
  56989. return this._boundingInfo.intersects(target._boundingInfo, false);
  56990. };
  56991. return SolidParticle;
  56992. }());
  56993. BABYLON.SolidParticle = SolidParticle;
  56994. /**
  56995. * Represents the shape of the model used by one particle of a solid particle system.
  56996. * SPS internal tool, don't use it manually.
  56997. */
  56998. var ModelShape = /** @class */ (function () {
  56999. /**
  57000. * 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.
  57001. * SPS internal tool, don't use it manually.
  57002. * @ignore
  57003. */
  57004. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57005. /**
  57006. * length of the shape in the model indices array (internal use)
  57007. */
  57008. this._indicesLength = 0;
  57009. this.shapeID = id;
  57010. this._shape = shape;
  57011. this._indicesLength = indicesLength;
  57012. this._shapeUV = shapeUV;
  57013. this._positionFunction = posFunction;
  57014. this._vertexFunction = vtxFunction;
  57015. }
  57016. return ModelShape;
  57017. }());
  57018. BABYLON.ModelShape = ModelShape;
  57019. /**
  57020. * Represents a Depth Sorted Particle in the solid particle system.
  57021. */
  57022. var DepthSortedParticle = /** @class */ (function () {
  57023. function DepthSortedParticle() {
  57024. /**
  57025. * Index of the particle in the "indices" array
  57026. */
  57027. this.ind = 0;
  57028. /**
  57029. * Length of the particle shape in the "indices" array
  57030. */
  57031. this.indicesLength = 0;
  57032. /**
  57033. * Squared distance from the particle to the camera
  57034. */
  57035. this.sqDistance = 0.0;
  57036. }
  57037. return DepthSortedParticle;
  57038. }());
  57039. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57040. })(BABYLON || (BABYLON = {}));
  57041. //# sourceMappingURL=babylon.solidParticle.js.map
  57042. var BABYLON;
  57043. (function (BABYLON) {
  57044. /**
  57045. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57046. *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.
  57047. * The SPS is also a particle system. It provides some methods to manage the particles.
  57048. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57049. *
  57050. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57051. */
  57052. var SolidParticleSystem = /** @class */ (function () {
  57053. /**
  57054. * Creates a SPS (Solid Particle System) object.
  57055. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57056. * @param scene (Scene) is the scene in which the SPS is added.
  57057. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57058. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57059. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57060. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57061. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57062. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57063. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57064. */
  57065. function SolidParticleSystem(name, scene, options) {
  57066. /**
  57067. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57068. * Example : var p = SPS.particles[i];
  57069. */
  57070. this.particles = new Array();
  57071. /**
  57072. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57073. */
  57074. this.nbParticles = 0;
  57075. /**
  57076. * If the particles must ever face the camera (default false). Useful for planar particles.
  57077. */
  57078. this.billboard = false;
  57079. /**
  57080. * Recompute normals when adding a shape
  57081. */
  57082. this.recomputeNormals = true;
  57083. /**
  57084. * This a counter ofr your own usage. It's not set by any SPS functions.
  57085. */
  57086. this.counter = 0;
  57087. /**
  57088. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57089. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57090. */
  57091. this.vars = {};
  57092. /**
  57093. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57094. */
  57095. this._bSphereOnly = false;
  57096. /**
  57097. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57098. */
  57099. this._bSphereRadiusFactor = 1.0;
  57100. this._positions = new Array();
  57101. this._indices = new Array();
  57102. this._normals = new Array();
  57103. this._colors = new Array();
  57104. this._uvs = new Array();
  57105. this._index = 0; // indices index
  57106. this._updatable = true;
  57107. this._pickable = false;
  57108. this._isVisibilityBoxLocked = false;
  57109. this._alwaysVisible = false;
  57110. this._depthSort = false;
  57111. this._shapeCounter = 0;
  57112. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57113. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57114. this._computeParticleColor = true;
  57115. this._computeParticleTexture = true;
  57116. this._computeParticleRotation = true;
  57117. this._computeParticleVertex = false;
  57118. this._computeBoundingBox = false;
  57119. this._depthSortParticles = true;
  57120. this._cam_axisZ = BABYLON.Vector3.Zero();
  57121. this._cam_axisY = BABYLON.Vector3.Zero();
  57122. this._cam_axisX = BABYLON.Vector3.Zero();
  57123. this._axisZ = BABYLON.Axis.Z;
  57124. this._camDir = BABYLON.Vector3.Zero();
  57125. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57126. this._rotMatrix = new BABYLON.Matrix();
  57127. this._invertMatrix = new BABYLON.Matrix();
  57128. this._rotated = BABYLON.Vector3.Zero();
  57129. this._quaternion = new BABYLON.Quaternion();
  57130. this._vertex = BABYLON.Vector3.Zero();
  57131. this._normal = BABYLON.Vector3.Zero();
  57132. this._yaw = 0.0;
  57133. this._pitch = 0.0;
  57134. this._roll = 0.0;
  57135. this._halfroll = 0.0;
  57136. this._halfpitch = 0.0;
  57137. this._halfyaw = 0.0;
  57138. this._sinRoll = 0.0;
  57139. this._cosRoll = 0.0;
  57140. this._sinPitch = 0.0;
  57141. this._cosPitch = 0.0;
  57142. this._sinYaw = 0.0;
  57143. this._cosYaw = 0.0;
  57144. this._mustUnrotateFixedNormals = false;
  57145. this._minimum = BABYLON.Vector3.Zero();
  57146. this._maximum = BABYLON.Vector3.Zero();
  57147. this._minBbox = BABYLON.Vector3.Zero();
  57148. this._maxBbox = BABYLON.Vector3.Zero();
  57149. this._particlesIntersect = false;
  57150. this._depthSortFunction = function (p1, p2) {
  57151. return (p2.sqDistance - p1.sqDistance);
  57152. };
  57153. this._needs32Bits = false;
  57154. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57155. this._scaledPivot = BABYLON.Vector3.Zero();
  57156. this._particleHasParent = false;
  57157. this.name = name;
  57158. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57159. this._camera = scene.activeCamera;
  57160. this._pickable = options ? options.isPickable : false;
  57161. this._depthSort = options ? options.enableDepthSort : false;
  57162. this._particlesIntersect = options ? options.particleIntersection : false;
  57163. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57164. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57165. if (options && options.updatable) {
  57166. this._updatable = options.updatable;
  57167. }
  57168. else {
  57169. this._updatable = true;
  57170. }
  57171. if (this._pickable) {
  57172. this.pickedParticles = [];
  57173. }
  57174. if (this._depthSort) {
  57175. this.depthSortedParticles = [];
  57176. }
  57177. }
  57178. /**
  57179. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57180. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57181. * @returns the created mesh
  57182. */
  57183. SolidParticleSystem.prototype.buildMesh = function () {
  57184. if (this.nbParticles === 0) {
  57185. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57186. this.addShape(triangle, 1);
  57187. triangle.dispose();
  57188. }
  57189. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57190. this._positions32 = new Float32Array(this._positions);
  57191. this._uvs32 = new Float32Array(this._uvs);
  57192. this._colors32 = new Float32Array(this._colors);
  57193. if (this.recomputeNormals) {
  57194. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57195. }
  57196. this._normals32 = new Float32Array(this._normals);
  57197. this._fixedNormal32 = new Float32Array(this._normals);
  57198. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57199. this._unrotateFixedNormals();
  57200. }
  57201. var vertexData = new BABYLON.VertexData();
  57202. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57203. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57204. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57205. if (this._uvs32) {
  57206. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57207. ;
  57208. }
  57209. if (this._colors32) {
  57210. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57211. }
  57212. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57213. vertexData.applyToMesh(mesh, this._updatable);
  57214. this.mesh = mesh;
  57215. this.mesh.isPickable = this._pickable;
  57216. // free memory
  57217. if (!this._depthSort) {
  57218. this._indices = null;
  57219. }
  57220. this._positions = null;
  57221. this._normals = null;
  57222. this._uvs = null;
  57223. this._colors = null;
  57224. if (!this._updatable) {
  57225. this.particles.length = 0;
  57226. }
  57227. return mesh;
  57228. };
  57229. /**
  57230. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57231. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57232. * Thus the particles generated from `digest()` have their property `position` set yet.
  57233. * @param mesh ( Mesh ) is the mesh to be digested
  57234. * @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
  57235. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57236. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57237. * @returns the current SPS
  57238. */
  57239. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57240. var size = (options && options.facetNb) || 1;
  57241. var number = (options && options.number) || 0;
  57242. var delta = (options && options.delta) || 0;
  57243. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57244. var meshInd = mesh.getIndices();
  57245. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57246. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57247. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57248. var f = 0; // facet counter
  57249. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57250. // compute size from number
  57251. if (number) {
  57252. number = (number > totalFacets) ? totalFacets : number;
  57253. size = Math.round(totalFacets / number);
  57254. delta = 0;
  57255. }
  57256. else {
  57257. size = (size > totalFacets) ? totalFacets : size;
  57258. }
  57259. var facetPos = []; // submesh positions
  57260. var facetInd = []; // submesh indices
  57261. var facetUV = []; // submesh UV
  57262. var facetCol = []; // submesh colors
  57263. var barycenter = BABYLON.Vector3.Zero();
  57264. var sizeO = size;
  57265. while (f < totalFacets) {
  57266. size = sizeO + Math.floor((1 + delta) * Math.random());
  57267. if (f > totalFacets - size) {
  57268. size = totalFacets - f;
  57269. }
  57270. // reset temp arrays
  57271. facetPos.length = 0;
  57272. facetInd.length = 0;
  57273. facetUV.length = 0;
  57274. facetCol.length = 0;
  57275. // iterate over "size" facets
  57276. var fi = 0;
  57277. for (var j = f * 3; j < (f + size) * 3; j++) {
  57278. facetInd.push(fi);
  57279. var i = meshInd[j];
  57280. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57281. if (meshUV) {
  57282. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57283. }
  57284. if (meshCol) {
  57285. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57286. }
  57287. fi++;
  57288. }
  57289. // create a model shape for each single particle
  57290. var idx = this.nbParticles;
  57291. var shape = this._posToShape(facetPos);
  57292. var shapeUV = this._uvsToShapeUV(facetUV);
  57293. // compute the barycenter of the shape
  57294. var v;
  57295. for (v = 0; v < shape.length; v++) {
  57296. barycenter.addInPlace(shape[v]);
  57297. }
  57298. barycenter.scaleInPlace(1 / shape.length);
  57299. // shift the shape from its barycenter to the origin
  57300. for (v = 0; v < shape.length; v++) {
  57301. shape[v].subtractInPlace(barycenter);
  57302. }
  57303. var bInfo;
  57304. if (this._particlesIntersect) {
  57305. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57306. }
  57307. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57308. // add the particle in the SPS
  57309. var currentPos = this._positions.length;
  57310. var currentInd = this._indices.length;
  57311. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57312. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57313. // initialize the particle position
  57314. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57315. this._index += shape.length;
  57316. idx++;
  57317. this.nbParticles++;
  57318. this._shapeCounter++;
  57319. f += size;
  57320. }
  57321. return this;
  57322. };
  57323. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57324. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57325. var index = 0;
  57326. var idx = 0;
  57327. for (var p = 0; p < this.particles.length; p++) {
  57328. this._particle = this.particles[p];
  57329. this._shape = this._particle._model._shape;
  57330. if (this._particle.rotationQuaternion) {
  57331. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57332. }
  57333. else {
  57334. this._yaw = this._particle.rotation.y;
  57335. this._pitch = this._particle.rotation.x;
  57336. this._roll = this._particle.rotation.z;
  57337. this._quaternionRotationYPR();
  57338. }
  57339. this._quaternionToRotationMatrix();
  57340. this._rotMatrix.invertToRef(this._invertMatrix);
  57341. for (var pt = 0; pt < this._shape.length; pt++) {
  57342. idx = index + pt * 3;
  57343. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57344. this._fixedNormal32[idx] = this._normal.x;
  57345. this._fixedNormal32[idx + 1] = this._normal.y;
  57346. this._fixedNormal32[idx + 2] = this._normal.z;
  57347. }
  57348. index = idx + 3;
  57349. }
  57350. };
  57351. //reset copy
  57352. SolidParticleSystem.prototype._resetCopy = function () {
  57353. this._copy.position.x = 0;
  57354. this._copy.position.y = 0;
  57355. this._copy.position.z = 0;
  57356. this._copy.rotation.x = 0;
  57357. this._copy.rotation.y = 0;
  57358. this._copy.rotation.z = 0;
  57359. this._copy.rotationQuaternion = null;
  57360. this._copy.scaling.x = 1.0;
  57361. this._copy.scaling.y = 1.0;
  57362. this._copy.scaling.z = 1.0;
  57363. this._copy.uvs.x = 0;
  57364. this._copy.uvs.y = 0;
  57365. this._copy.uvs.z = 1.0;
  57366. this._copy.uvs.w = 1.0;
  57367. this._copy.color = null;
  57368. this._copy.translateFromPivot = false;
  57369. };
  57370. // _meshBuilder : inserts the shape model in the global SPS mesh
  57371. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57372. var i;
  57373. var u = 0;
  57374. var c = 0;
  57375. var n = 0;
  57376. this._resetCopy();
  57377. if (options && options.positionFunction) { // call to custom positionFunction
  57378. options.positionFunction(this._copy, idx, idxInShape);
  57379. this._mustUnrotateFixedNormals = true;
  57380. }
  57381. if (this._copy.rotationQuaternion) {
  57382. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57383. }
  57384. else {
  57385. this._yaw = this._copy.rotation.y;
  57386. this._pitch = this._copy.rotation.x;
  57387. this._roll = this._copy.rotation.z;
  57388. this._quaternionRotationYPR();
  57389. }
  57390. this._quaternionToRotationMatrix();
  57391. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57392. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57393. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57394. if (this._copy.translateFromPivot) {
  57395. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57396. }
  57397. else {
  57398. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57399. }
  57400. for (i = 0; i < shape.length; i++) {
  57401. this._vertex.x = shape[i].x;
  57402. this._vertex.y = shape[i].y;
  57403. this._vertex.z = shape[i].z;
  57404. if (options && options.vertexFunction) {
  57405. options.vertexFunction(this._copy, this._vertex, i);
  57406. }
  57407. this._vertex.x *= this._copy.scaling.x;
  57408. this._vertex.y *= this._copy.scaling.y;
  57409. this._vertex.z *= this._copy.scaling.z;
  57410. this._vertex.x -= this._scaledPivot.x;
  57411. this._vertex.y -= this._scaledPivot.y;
  57412. this._vertex.z -= this._scaledPivot.z;
  57413. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57414. this._rotated.addInPlace(this._pivotBackTranslation);
  57415. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57416. if (meshUV) {
  57417. 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);
  57418. u += 2;
  57419. }
  57420. if (this._copy.color) {
  57421. this._color = this._copy.color;
  57422. }
  57423. else if (meshCol && meshCol[c] !== undefined) {
  57424. this._color.r = meshCol[c];
  57425. this._color.g = meshCol[c + 1];
  57426. this._color.b = meshCol[c + 2];
  57427. this._color.a = meshCol[c + 3];
  57428. }
  57429. else {
  57430. this._color.r = 1.0;
  57431. this._color.g = 1.0;
  57432. this._color.b = 1.0;
  57433. this._color.a = 1.0;
  57434. }
  57435. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57436. c += 4;
  57437. if (!this.recomputeNormals && meshNor) {
  57438. this._normal.x = meshNor[n];
  57439. this._normal.y = meshNor[n + 1];
  57440. this._normal.z = meshNor[n + 2];
  57441. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57442. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57443. n += 3;
  57444. }
  57445. }
  57446. for (i = 0; i < meshInd.length; i++) {
  57447. var current_ind = p + meshInd[i];
  57448. indices.push(current_ind);
  57449. if (current_ind > 65535) {
  57450. this._needs32Bits = true;
  57451. }
  57452. }
  57453. if (this._pickable) {
  57454. var nbfaces = meshInd.length / 3;
  57455. for (i = 0; i < nbfaces; i++) {
  57456. this.pickedParticles.push({ idx: idx, faceId: i });
  57457. }
  57458. }
  57459. if (this._depthSort) {
  57460. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57461. }
  57462. return this._copy;
  57463. };
  57464. // returns a shape array from positions array
  57465. SolidParticleSystem.prototype._posToShape = function (positions) {
  57466. var shape = [];
  57467. for (var i = 0; i < positions.length; i += 3) {
  57468. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57469. }
  57470. return shape;
  57471. };
  57472. // returns a shapeUV array from a Vector4 uvs
  57473. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57474. var shapeUV = [];
  57475. if (uvs) {
  57476. for (var i = 0; i < uvs.length; i++)
  57477. shapeUV.push(uvs[i]);
  57478. }
  57479. return shapeUV;
  57480. };
  57481. // adds a new particle object in the particles array
  57482. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57483. if (bInfo === void 0) { bInfo = null; }
  57484. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57485. this.particles.push(sp);
  57486. return sp;
  57487. };
  57488. /**
  57489. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57490. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57491. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57492. * @param nb (positive integer) the number of particles to be created from this model
  57493. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57494. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57495. * @returns the number of shapes in the system
  57496. */
  57497. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57498. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57499. var meshInd = mesh.getIndices();
  57500. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57501. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57502. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57503. var bbInfo;
  57504. if (this._particlesIntersect) {
  57505. bbInfo = mesh.getBoundingInfo();
  57506. }
  57507. var shape = this._posToShape(meshPos);
  57508. var shapeUV = this._uvsToShapeUV(meshUV);
  57509. var posfunc = options ? options.positionFunction : null;
  57510. var vtxfunc = options ? options.vertexFunction : null;
  57511. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57512. // particles
  57513. var sp;
  57514. var currentCopy;
  57515. var idx = this.nbParticles;
  57516. for (var i = 0; i < nb; i++) {
  57517. var currentPos = this._positions.length;
  57518. var currentInd = this._indices.length;
  57519. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57520. if (this._updatable) {
  57521. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57522. sp.position.copyFrom(currentCopy.position);
  57523. sp.rotation.copyFrom(currentCopy.rotation);
  57524. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57525. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57526. }
  57527. if (currentCopy.color && sp.color) {
  57528. sp.color.copyFrom(currentCopy.color);
  57529. }
  57530. sp.scaling.copyFrom(currentCopy.scaling);
  57531. sp.uvs.copyFrom(currentCopy.uvs);
  57532. }
  57533. this._index += shape.length;
  57534. idx++;
  57535. }
  57536. this.nbParticles += nb;
  57537. this._shapeCounter++;
  57538. return this._shapeCounter - 1;
  57539. };
  57540. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57541. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57542. this._resetCopy();
  57543. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57544. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57545. }
  57546. if (this._copy.rotationQuaternion) {
  57547. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57548. }
  57549. else {
  57550. this._yaw = this._copy.rotation.y;
  57551. this._pitch = this._copy.rotation.x;
  57552. this._roll = this._copy.rotation.z;
  57553. this._quaternionRotationYPR();
  57554. }
  57555. this._quaternionToRotationMatrix();
  57556. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57557. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57558. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57559. if (this._copy.translateFromPivot) {
  57560. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57561. }
  57562. else {
  57563. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57564. }
  57565. this._shape = particle._model._shape;
  57566. for (var pt = 0; pt < this._shape.length; pt++) {
  57567. this._vertex.x = this._shape[pt].x;
  57568. this._vertex.y = this._shape[pt].y;
  57569. this._vertex.z = this._shape[pt].z;
  57570. if (particle._model._vertexFunction) {
  57571. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57572. }
  57573. this._vertex.x *= this._copy.scaling.x;
  57574. this._vertex.y *= this._copy.scaling.y;
  57575. this._vertex.z *= this._copy.scaling.z;
  57576. this._vertex.x -= this._scaledPivot.x;
  57577. this._vertex.y -= this._scaledPivot.y;
  57578. this._vertex.z -= this._scaledPivot.z;
  57579. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57580. this._rotated.addInPlace(this._pivotBackTranslation);
  57581. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57582. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57583. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57584. }
  57585. particle.position.x = 0.0;
  57586. particle.position.y = 0.0;
  57587. particle.position.z = 0.0;
  57588. particle.rotation.x = 0.0;
  57589. particle.rotation.y = 0.0;
  57590. particle.rotation.z = 0.0;
  57591. particle.rotationQuaternion = null;
  57592. particle.scaling.x = 1.0;
  57593. particle.scaling.y = 1.0;
  57594. particle.scaling.z = 1.0;
  57595. particle.uvs.x = 0.0;
  57596. particle.uvs.y = 0.0;
  57597. particle.uvs.z = 1.0;
  57598. particle.uvs.w = 1.0;
  57599. particle.pivot.x = 0.0;
  57600. particle.pivot.y = 0.0;
  57601. particle.pivot.z = 0.0;
  57602. particle.translateFromPivot = false;
  57603. particle.parentId = null;
  57604. };
  57605. /**
  57606. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57607. * @returns the SPS.
  57608. */
  57609. SolidParticleSystem.prototype.rebuildMesh = function () {
  57610. for (var p = 0; p < this.particles.length; p++) {
  57611. this._rebuildParticle(this.particles[p]);
  57612. }
  57613. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57614. return this;
  57615. };
  57616. /**
  57617. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57618. * This method calls `updateParticle()` for each particle of the SPS.
  57619. * For an animated SPS, it is usually called within the render loop.
  57620. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57621. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57622. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57623. * @returns the SPS.
  57624. */
  57625. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57626. if (start === void 0) { start = 0; }
  57627. if (end === void 0) { end = this.nbParticles - 1; }
  57628. if (update === void 0) { update = true; }
  57629. if (!this._updatable) {
  57630. return this;
  57631. }
  57632. // custom beforeUpdate
  57633. this.beforeUpdateParticles(start, end, update);
  57634. this._cam_axisX.x = 1.0;
  57635. this._cam_axisX.y = 0.0;
  57636. this._cam_axisX.z = 0.0;
  57637. this._cam_axisY.x = 0.0;
  57638. this._cam_axisY.y = 1.0;
  57639. this._cam_axisY.z = 0.0;
  57640. this._cam_axisZ.x = 0.0;
  57641. this._cam_axisZ.y = 0.0;
  57642. this._cam_axisZ.z = 1.0;
  57643. // cases when the World Matrix is to be computed first
  57644. if (this.billboard || this._depthSort) {
  57645. this.mesh.computeWorldMatrix(true);
  57646. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57647. }
  57648. // if the particles will always face the camera
  57649. if (this.billboard) {
  57650. // compute the camera position and un-rotate it by the current mesh rotation
  57651. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57652. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57653. this._cam_axisZ.normalize();
  57654. // same for camera up vector extracted from the cam view matrix
  57655. var view = this._camera.getViewMatrix(true);
  57656. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57657. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57658. this._cam_axisY.normalize();
  57659. this._cam_axisX.normalize();
  57660. }
  57661. // if depthSort, compute the camera global position in the mesh local system
  57662. if (this._depthSort) {
  57663. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57664. }
  57665. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57666. var idx = 0; // current position index in the global array positions32
  57667. var index = 0; // position start index in the global array positions32 of the current particle
  57668. var colidx = 0; // current color index in the global array colors32
  57669. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57670. var uvidx = 0; // current uv index in the global array uvs32
  57671. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57672. var pt = 0; // current index in the particle model shape
  57673. if (this.mesh.isFacetDataEnabled) {
  57674. this._computeBoundingBox = true;
  57675. }
  57676. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57677. if (this._computeBoundingBox) {
  57678. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  57679. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57680. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57681. }
  57682. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  57683. if (this.mesh._boundingInfo) {
  57684. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57685. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57686. }
  57687. }
  57688. }
  57689. // particle loop
  57690. index = this.particles[start]._pos;
  57691. var vpos = (index / 3) | 0;
  57692. colorIndex = vpos * 4;
  57693. uvIndex = vpos * 2;
  57694. for (var p = start; p <= end; p++) {
  57695. this._particle = this.particles[p];
  57696. this._shape = this._particle._model._shape;
  57697. this._shapeUV = this._particle._model._shapeUV;
  57698. // call to custom user function to update the particle properties
  57699. this.updateParticle(this._particle);
  57700. // camera-particle distance for depth sorting
  57701. if (this._depthSort && this._depthSortParticles) {
  57702. var dsp = this.depthSortedParticles[p];
  57703. dsp.ind = this._particle._ind;
  57704. dsp.indicesLength = this._particle._model._indicesLength;
  57705. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57706. }
  57707. // skip the computations for inactive or already invisible particles
  57708. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57709. // increment indexes for the next particle
  57710. pt = this._shape.length;
  57711. index += pt * 3;
  57712. colorIndex += pt * 4;
  57713. uvIndex += pt * 2;
  57714. continue;
  57715. }
  57716. if (this._particle.isVisible) {
  57717. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57718. this._particleHasParent = (this._particle.parentId !== null);
  57719. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57720. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57721. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57722. // particle rotation matrix
  57723. if (this.billboard) {
  57724. this._particle.rotation.x = 0.0;
  57725. this._particle.rotation.y = 0.0;
  57726. }
  57727. if (this._computeParticleRotation || this.billboard) {
  57728. if (this._particle.rotationQuaternion) {
  57729. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57730. }
  57731. else {
  57732. this._yaw = this._particle.rotation.y;
  57733. this._pitch = this._particle.rotation.x;
  57734. this._roll = this._particle.rotation.z;
  57735. this._quaternionRotationYPR();
  57736. }
  57737. this._quaternionToRotationMatrix();
  57738. }
  57739. if (this._particleHasParent) {
  57740. this._parent = this.particles[this._particle.parentId];
  57741. 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];
  57742. 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];
  57743. 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];
  57744. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57745. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57746. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57747. if (this._computeParticleRotation || this.billboard) {
  57748. 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];
  57749. 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];
  57750. 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];
  57751. 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];
  57752. 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];
  57753. 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];
  57754. 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];
  57755. 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];
  57756. 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];
  57757. }
  57758. }
  57759. else {
  57760. this._particle._globalPosition.x = this._particle.position.x;
  57761. this._particle._globalPosition.y = this._particle.position.y;
  57762. this._particle._globalPosition.z = this._particle.position.z;
  57763. if (this._computeParticleRotation || this.billboard) {
  57764. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57765. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57766. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57767. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57768. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57769. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57770. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57771. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57772. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57773. }
  57774. }
  57775. if (this._particle.translateFromPivot) {
  57776. this._pivotBackTranslation.x = 0.0;
  57777. this._pivotBackTranslation.y = 0.0;
  57778. this._pivotBackTranslation.z = 0.0;
  57779. }
  57780. else {
  57781. this._pivotBackTranslation.x = this._scaledPivot.x;
  57782. this._pivotBackTranslation.y = this._scaledPivot.y;
  57783. this._pivotBackTranslation.z = this._scaledPivot.z;
  57784. }
  57785. // particle vertex loop
  57786. for (pt = 0; pt < this._shape.length; pt++) {
  57787. idx = index + pt * 3;
  57788. colidx = colorIndex + pt * 4;
  57789. uvidx = uvIndex + pt * 2;
  57790. this._vertex.x = this._shape[pt].x;
  57791. this._vertex.y = this._shape[pt].y;
  57792. this._vertex.z = this._shape[pt].z;
  57793. if (this._computeParticleVertex) {
  57794. this.updateParticleVertex(this._particle, this._vertex, pt);
  57795. }
  57796. // positions
  57797. this._vertex.x *= this._particle.scaling.x;
  57798. this._vertex.y *= this._particle.scaling.y;
  57799. this._vertex.z *= this._particle.scaling.z;
  57800. this._vertex.x -= this._scaledPivot.x;
  57801. this._vertex.y -= this._scaledPivot.y;
  57802. this._vertex.z -= this._scaledPivot.z;
  57803. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57804. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57805. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57806. this._rotated.x += this._pivotBackTranslation.x;
  57807. this._rotated.y += this._pivotBackTranslation.y;
  57808. this._rotated.z += this._pivotBackTranslation.z;
  57809. 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;
  57810. 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;
  57811. 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;
  57812. if (this._computeBoundingBox) {
  57813. if (this._positions32[idx] < this._minimum.x) {
  57814. this._minimum.x = this._positions32[idx];
  57815. }
  57816. if (this._positions32[idx] > this._maximum.x) {
  57817. this._maximum.x = this._positions32[idx];
  57818. }
  57819. if (this._positions32[idx + 1] < this._minimum.y) {
  57820. this._minimum.y = this._positions32[idx + 1];
  57821. }
  57822. if (this._positions32[idx + 1] > this._maximum.y) {
  57823. this._maximum.y = this._positions32[idx + 1];
  57824. }
  57825. if (this._positions32[idx + 2] < this._minimum.z) {
  57826. this._minimum.z = this._positions32[idx + 2];
  57827. }
  57828. if (this._positions32[idx + 2] > this._maximum.z) {
  57829. this._maximum.z = this._positions32[idx + 2];
  57830. }
  57831. }
  57832. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57833. if (!this._computeParticleVertex) {
  57834. this._normal.x = this._fixedNormal32[idx];
  57835. this._normal.y = this._fixedNormal32[idx + 1];
  57836. this._normal.z = this._fixedNormal32[idx + 2];
  57837. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57838. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57839. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57840. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57841. 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;
  57842. 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;
  57843. }
  57844. if (this._computeParticleColor && this._particle.color) {
  57845. this._colors32[colidx] = this._particle.color.r;
  57846. this._colors32[colidx + 1] = this._particle.color.g;
  57847. this._colors32[colidx + 2] = this._particle.color.b;
  57848. this._colors32[colidx + 3] = this._particle.color.a;
  57849. }
  57850. if (this._computeParticleTexture) {
  57851. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57852. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57853. }
  57854. }
  57855. }
  57856. // particle just set invisible : scaled to zero and positioned at the origin
  57857. else {
  57858. this._particle._stillInvisible = true; // mark the particle as invisible
  57859. for (pt = 0; pt < this._shape.length; pt++) {
  57860. idx = index + pt * 3;
  57861. colidx = colorIndex + pt * 4;
  57862. uvidx = uvIndex + pt * 2;
  57863. this._positions32[idx] = 0.0;
  57864. this._positions32[idx + 1] = 0.0;
  57865. this._positions32[idx + 2] = 0.0;
  57866. this._normals32[idx] = 0.0;
  57867. this._normals32[idx + 1] = 0.0;
  57868. this._normals32[idx + 2] = 0.0;
  57869. if (this._computeParticleColor && this._particle.color) {
  57870. this._colors32[colidx] = this._particle.color.r;
  57871. this._colors32[colidx + 1] = this._particle.color.g;
  57872. this._colors32[colidx + 2] = this._particle.color.b;
  57873. this._colors32[colidx + 3] = this._particle.color.a;
  57874. }
  57875. if (this._computeParticleTexture) {
  57876. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57877. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57878. }
  57879. }
  57880. }
  57881. // if the particle intersections must be computed : update the bbInfo
  57882. if (this._particlesIntersect) {
  57883. var bInfo = this._particle._boundingInfo;
  57884. var bBox = bInfo.boundingBox;
  57885. var bSphere = bInfo.boundingSphere;
  57886. if (!this._bSphereOnly) {
  57887. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57888. for (var b = 0; b < bBox.vectors.length; b++) {
  57889. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57890. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57891. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57892. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57893. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57894. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57895. 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;
  57896. 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;
  57897. 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;
  57898. }
  57899. bBox._update(this.mesh._worldMatrix);
  57900. }
  57901. // place and scale the particle bouding sphere in the SPS local system, then update it
  57902. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57903. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57904. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57905. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57906. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57907. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57908. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57909. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57910. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57911. 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));
  57912. bSphere._update(this.mesh._worldMatrix);
  57913. }
  57914. // increment indexes for the next particle
  57915. index = idx + 3;
  57916. colorIndex = colidx + 4;
  57917. uvIndex = uvidx + 2;
  57918. }
  57919. // if the VBO must be updated
  57920. if (update) {
  57921. if (this._computeParticleColor) {
  57922. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57923. }
  57924. if (this._computeParticleTexture) {
  57925. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57926. }
  57927. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57928. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57929. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57930. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57931. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57932. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57933. for (var i = 0; i < this._normals32.length; i++) {
  57934. this._fixedNormal32[i] = this._normals32[i];
  57935. }
  57936. }
  57937. if (!this.mesh.areNormalsFrozen) {
  57938. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57939. }
  57940. }
  57941. if (this._depthSort && this._depthSortParticles) {
  57942. this.depthSortedParticles.sort(this._depthSortFunction);
  57943. var dspl = this.depthSortedParticles.length;
  57944. var sorted = 0;
  57945. var lind = 0;
  57946. var sind = 0;
  57947. var sid = 0;
  57948. for (sorted = 0; sorted < dspl; sorted++) {
  57949. lind = this.depthSortedParticles[sorted].indicesLength;
  57950. sind = this.depthSortedParticles[sorted].ind;
  57951. for (var i = 0; i < lind; i++) {
  57952. this._indices32[sid] = this._indices[sind + i];
  57953. sid++;
  57954. }
  57955. }
  57956. this.mesh.updateIndices(this._indices32);
  57957. }
  57958. }
  57959. if (this._computeBoundingBox) {
  57960. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57961. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57962. }
  57963. this.afterUpdateParticles(start, end, update);
  57964. return this;
  57965. };
  57966. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57967. this._halfroll = this._roll * 0.5;
  57968. this._halfpitch = this._pitch * 0.5;
  57969. this._halfyaw = this._yaw * 0.5;
  57970. this._sinRoll = Math.sin(this._halfroll);
  57971. this._cosRoll = Math.cos(this._halfroll);
  57972. this._sinPitch = Math.sin(this._halfpitch);
  57973. this._cosPitch = Math.cos(this._halfpitch);
  57974. this._sinYaw = Math.sin(this._halfyaw);
  57975. this._cosYaw = Math.cos(this._halfyaw);
  57976. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57977. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57978. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57979. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57980. };
  57981. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57982. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57983. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57984. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57985. this._rotMatrix.m[3] = 0;
  57986. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57987. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57988. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57989. this._rotMatrix.m[7] = 0;
  57990. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57991. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57992. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57993. this._rotMatrix.m[11] = 0;
  57994. this._rotMatrix.m[12] = 0;
  57995. this._rotMatrix.m[13] = 0;
  57996. this._rotMatrix.m[14] = 0;
  57997. this._rotMatrix.m[15] = 1.0;
  57998. };
  57999. /**
  58000. * Disposes the SPS.
  58001. */
  58002. SolidParticleSystem.prototype.dispose = function () {
  58003. this.mesh.dispose();
  58004. this.vars = null;
  58005. // drop references to internal big arrays for the GC
  58006. this._positions = null;
  58007. this._indices = null;
  58008. this._normals = null;
  58009. this._uvs = null;
  58010. this._colors = null;
  58011. this._indices32 = null;
  58012. this._positions32 = null;
  58013. this._normals32 = null;
  58014. this._fixedNormal32 = null;
  58015. this._uvs32 = null;
  58016. this._colors32 = null;
  58017. this.pickedParticles = null;
  58018. };
  58019. /**
  58020. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58021. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58022. * @returns the SPS.
  58023. */
  58024. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58025. if (!this._isVisibilityBoxLocked) {
  58026. this.mesh.refreshBoundingInfo();
  58027. }
  58028. return this;
  58029. };
  58030. /**
  58031. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58032. * @param size the size (float) of the visibility box
  58033. * note : this doesn't lock the SPS mesh bounding box.
  58034. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58035. */
  58036. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58037. var vis = size / 2;
  58038. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58039. };
  58040. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58041. /**
  58042. * Gets whether the SPS as always visible or not
  58043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58044. */
  58045. get: function () {
  58046. return this._alwaysVisible;
  58047. },
  58048. /**
  58049. * Sets the SPS as always visible or not
  58050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58051. */
  58052. set: function (val) {
  58053. this._alwaysVisible = val;
  58054. this.mesh.alwaysSelectAsActiveMesh = val;
  58055. },
  58056. enumerable: true,
  58057. configurable: true
  58058. });
  58059. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58060. /**
  58061. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58062. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58063. */
  58064. get: function () {
  58065. return this._isVisibilityBoxLocked;
  58066. },
  58067. /**
  58068. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58070. */
  58071. set: function (val) {
  58072. this._isVisibilityBoxLocked = val;
  58073. var boundingInfo = this.mesh.getBoundingInfo();
  58074. boundingInfo.isLocked = val;
  58075. },
  58076. enumerable: true,
  58077. configurable: true
  58078. });
  58079. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58080. /**
  58081. * Gets if `setParticles()` computes the particle rotations or not.
  58082. * Default value : true. The SPS is faster when it's set to false.
  58083. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58084. */
  58085. get: function () {
  58086. return this._computeParticleRotation;
  58087. },
  58088. /**
  58089. * Tells to `setParticles()` to compute the particle rotations or not.
  58090. * Default value : true. The SPS is faster when it's set to false.
  58091. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58092. */
  58093. set: function (val) {
  58094. this._computeParticleRotation = val;
  58095. },
  58096. enumerable: true,
  58097. configurable: true
  58098. });
  58099. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58100. /**
  58101. * Gets if `setParticles()` computes the particle colors or not.
  58102. * Default value : true. The SPS is faster when it's set to false.
  58103. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58104. */
  58105. get: function () {
  58106. return this._computeParticleColor;
  58107. },
  58108. /**
  58109. * Tells to `setParticles()` to compute the particle colors or not.
  58110. * Default value : true. The SPS is faster when it's set to false.
  58111. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58112. */
  58113. set: function (val) {
  58114. this._computeParticleColor = val;
  58115. },
  58116. enumerable: true,
  58117. configurable: true
  58118. });
  58119. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58120. /**
  58121. * Gets if `setParticles()` computes the particle textures or not.
  58122. * Default value : true. The SPS is faster when it's set to false.
  58123. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58124. */
  58125. get: function () {
  58126. return this._computeParticleTexture;
  58127. },
  58128. set: function (val) {
  58129. this._computeParticleTexture = val;
  58130. },
  58131. enumerable: true,
  58132. configurable: true
  58133. });
  58134. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58135. /**
  58136. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58137. * Default value : false. The SPS is faster when it's set to false.
  58138. * Note : the particle custom vertex positions aren't stored values.
  58139. */
  58140. get: function () {
  58141. return this._computeParticleVertex;
  58142. },
  58143. /**
  58144. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58145. * Default value : false. The SPS is faster when it's set to false.
  58146. * Note : the particle custom vertex positions aren't stored values.
  58147. */
  58148. set: function (val) {
  58149. this._computeParticleVertex = val;
  58150. },
  58151. enumerable: true,
  58152. configurable: true
  58153. });
  58154. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58155. /**
  58156. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58157. */
  58158. get: function () {
  58159. return this._computeBoundingBox;
  58160. },
  58161. /**
  58162. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58163. */
  58164. set: function (val) {
  58165. this._computeBoundingBox = val;
  58166. },
  58167. enumerable: true,
  58168. configurable: true
  58169. });
  58170. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58171. /**
  58172. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58173. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58174. * Default : `true`
  58175. */
  58176. get: function () {
  58177. return this._depthSortParticles;
  58178. },
  58179. /**
  58180. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58181. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58182. * Default : `true`
  58183. */
  58184. set: function (val) {
  58185. this._depthSortParticles = val;
  58186. },
  58187. enumerable: true,
  58188. configurable: true
  58189. });
  58190. // =======================================================================
  58191. // Particle behavior logic
  58192. // these following methods may be overwritten by the user to fit his needs
  58193. /**
  58194. * This function does nothing. It may be overwritten to set all the particle first values.
  58195. * The SPS doesn't call this function, you may have to call it by your own.
  58196. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58197. */
  58198. SolidParticleSystem.prototype.initParticles = function () {
  58199. };
  58200. /**
  58201. * This function does nothing. It may be overwritten to recycle a particle.
  58202. * The SPS doesn't call this function, you may have to call it by your own.
  58203. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58204. * @param particle The particle to recycle
  58205. * @returns the recycled particle
  58206. */
  58207. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58208. return particle;
  58209. };
  58210. /**
  58211. * Updates a particle : this function should be overwritten by the user.
  58212. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58213. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58214. * @example : just set a particle position or velocity and recycle conditions
  58215. * @param particle The particle to update
  58216. * @returns the updated particle
  58217. */
  58218. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58219. return particle;
  58220. };
  58221. /**
  58222. * Updates a vertex of a particle : it can be overwritten by the user.
  58223. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58224. * @param particle the current particle
  58225. * @param vertex the current index of the current particle
  58226. * @param pt the index of the current vertex in the particle shape
  58227. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58228. * @example : just set a vertex particle position
  58229. * @returns the updated vertex
  58230. */
  58231. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58232. return vertex;
  58233. };
  58234. /**
  58235. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58236. * This does nothing and may be overwritten by the user.
  58237. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58238. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58239. * @param update the boolean update value actually passed to setParticles()
  58240. */
  58241. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58242. };
  58243. /**
  58244. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58245. * This will be passed three parameters.
  58246. * This does nothing and may be overwritten by the user.
  58247. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58248. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58249. * @param update the boolean update value actually passed to setParticles()
  58250. */
  58251. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58252. };
  58253. return SolidParticleSystem;
  58254. }());
  58255. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58256. })(BABYLON || (BABYLON = {}));
  58257. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58258. var BABYLON;
  58259. (function (BABYLON) {
  58260. var ShaderMaterial = /** @class */ (function (_super) {
  58261. __extends(ShaderMaterial, _super);
  58262. function ShaderMaterial(name, scene, shaderPath, options) {
  58263. var _this = _super.call(this, name, scene) || this;
  58264. _this._textures = {};
  58265. _this._textureArrays = {};
  58266. _this._floats = {};
  58267. _this._ints = {};
  58268. _this._floatsArrays = {};
  58269. _this._colors3 = {};
  58270. _this._colors3Arrays = {};
  58271. _this._colors4 = {};
  58272. _this._vectors2 = {};
  58273. _this._vectors3 = {};
  58274. _this._vectors4 = {};
  58275. _this._matrices = {};
  58276. _this._matrices3x3 = {};
  58277. _this._matrices2x2 = {};
  58278. _this._vectors2Arrays = {};
  58279. _this._vectors3Arrays = {};
  58280. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58281. _this._shaderPath = shaderPath;
  58282. options.needAlphaBlending = options.needAlphaBlending || false;
  58283. options.needAlphaTesting = options.needAlphaTesting || false;
  58284. options.attributes = options.attributes || ["position", "normal", "uv"];
  58285. options.uniforms = options.uniforms || ["worldViewProjection"];
  58286. options.uniformBuffers = options.uniformBuffers || [];
  58287. options.samplers = options.samplers || [];
  58288. options.defines = options.defines || [];
  58289. _this._options = options;
  58290. return _this;
  58291. }
  58292. ShaderMaterial.prototype.getClassName = function () {
  58293. return "ShaderMaterial";
  58294. };
  58295. ShaderMaterial.prototype.needAlphaBlending = function () {
  58296. return this._options.needAlphaBlending;
  58297. };
  58298. ShaderMaterial.prototype.needAlphaTesting = function () {
  58299. return this._options.needAlphaTesting;
  58300. };
  58301. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58302. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58303. this._options.uniforms.push(uniformName);
  58304. }
  58305. };
  58306. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58307. if (this._options.samplers.indexOf(name) === -1) {
  58308. this._options.samplers.push(name);
  58309. }
  58310. this._textures[name] = texture;
  58311. return this;
  58312. };
  58313. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58314. if (this._options.samplers.indexOf(name) === -1) {
  58315. this._options.samplers.push(name);
  58316. }
  58317. this._checkUniform(name);
  58318. this._textureArrays[name] = textures;
  58319. return this;
  58320. };
  58321. ShaderMaterial.prototype.setFloat = function (name, value) {
  58322. this._checkUniform(name);
  58323. this._floats[name] = value;
  58324. return this;
  58325. };
  58326. ShaderMaterial.prototype.setInt = function (name, value) {
  58327. this._checkUniform(name);
  58328. this._ints[name] = value;
  58329. return this;
  58330. };
  58331. ShaderMaterial.prototype.setFloats = function (name, value) {
  58332. this._checkUniform(name);
  58333. this._floatsArrays[name] = value;
  58334. return this;
  58335. };
  58336. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58337. this._checkUniform(name);
  58338. this._colors3[name] = value;
  58339. return this;
  58340. };
  58341. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58342. this._checkUniform(name);
  58343. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58344. color.toArray(arr, arr.length);
  58345. return arr;
  58346. }, []);
  58347. return this;
  58348. };
  58349. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58350. this._checkUniform(name);
  58351. this._colors4[name] = value;
  58352. return this;
  58353. };
  58354. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58355. this._checkUniform(name);
  58356. this._vectors2[name] = value;
  58357. return this;
  58358. };
  58359. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58360. this._checkUniform(name);
  58361. this._vectors3[name] = value;
  58362. return this;
  58363. };
  58364. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58365. this._checkUniform(name);
  58366. this._vectors4[name] = value;
  58367. return this;
  58368. };
  58369. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58370. this._checkUniform(name);
  58371. this._matrices[name] = value;
  58372. return this;
  58373. };
  58374. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58375. this._checkUniform(name);
  58376. this._matrices3x3[name] = value;
  58377. return this;
  58378. };
  58379. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58380. this._checkUniform(name);
  58381. this._matrices2x2[name] = value;
  58382. return this;
  58383. };
  58384. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58385. this._checkUniform(name);
  58386. this._vectors2Arrays[name] = value;
  58387. return this;
  58388. };
  58389. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58390. this._checkUniform(name);
  58391. this._vectors3Arrays[name] = value;
  58392. return this;
  58393. };
  58394. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58395. if (!mesh) {
  58396. return true;
  58397. }
  58398. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58399. return false;
  58400. }
  58401. return false;
  58402. };
  58403. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58404. var scene = this.getScene();
  58405. var engine = scene.getEngine();
  58406. if (!this.checkReadyOnEveryCall) {
  58407. if (this._renderId === scene.getRenderId()) {
  58408. if (this._checkCache(scene, mesh, useInstances)) {
  58409. return true;
  58410. }
  58411. }
  58412. }
  58413. // Instances
  58414. var defines = [];
  58415. var attribs = [];
  58416. var fallbacks = new BABYLON.EffectFallbacks();
  58417. if (useInstances) {
  58418. defines.push("#define INSTANCES");
  58419. }
  58420. for (var index = 0; index < this._options.defines.length; index++) {
  58421. defines.push(this._options.defines[index]);
  58422. }
  58423. for (var index = 0; index < this._options.attributes.length; index++) {
  58424. attribs.push(this._options.attributes[index]);
  58425. }
  58426. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58427. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58428. defines.push("#define VERTEXCOLOR");
  58429. }
  58430. // Bones
  58431. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58432. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58433. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58434. if (mesh.numBoneInfluencers > 4) {
  58435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58437. }
  58438. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58439. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58440. fallbacks.addCPUSkinningFallback(0, mesh);
  58441. if (this._options.uniforms.indexOf("mBones") === -1) {
  58442. this._options.uniforms.push("mBones");
  58443. }
  58444. }
  58445. else {
  58446. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58447. }
  58448. // Textures
  58449. for (var name in this._textures) {
  58450. if (!this._textures[name].isReady()) {
  58451. return false;
  58452. }
  58453. }
  58454. // Alpha test
  58455. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58456. defines.push("#define ALPHATEST");
  58457. }
  58458. var previousEffect = this._effect;
  58459. var join = defines.join("\n");
  58460. this._effect = engine.createEffect(this._shaderPath, {
  58461. attributes: attribs,
  58462. uniformsNames: this._options.uniforms,
  58463. uniformBuffersNames: this._options.uniformBuffers,
  58464. samplers: this._options.samplers,
  58465. defines: join,
  58466. fallbacks: fallbacks,
  58467. onCompiled: this.onCompiled,
  58468. onError: this.onError
  58469. }, engine);
  58470. if (!this._effect.isReady()) {
  58471. return false;
  58472. }
  58473. if (previousEffect !== this._effect) {
  58474. scene.resetCachedMaterial();
  58475. }
  58476. this._renderId = scene.getRenderId();
  58477. return true;
  58478. };
  58479. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58480. var scene = this.getScene();
  58481. if (!this._effect) {
  58482. return;
  58483. }
  58484. if (this._options.uniforms.indexOf("world") !== -1) {
  58485. this._effect.setMatrix("world", world);
  58486. }
  58487. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58488. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58489. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58490. }
  58491. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58492. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58493. }
  58494. };
  58495. ShaderMaterial.prototype.bind = function (world, mesh) {
  58496. // Std values
  58497. this.bindOnlyWorldMatrix(world);
  58498. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58499. if (this._options.uniforms.indexOf("view") !== -1) {
  58500. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58501. }
  58502. if (this._options.uniforms.indexOf("projection") !== -1) {
  58503. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58504. }
  58505. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58506. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58507. }
  58508. // Bones
  58509. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58510. var name;
  58511. // Texture
  58512. for (name in this._textures) {
  58513. this._effect.setTexture(name, this._textures[name]);
  58514. }
  58515. // Texture arrays
  58516. for (name in this._textureArrays) {
  58517. this._effect.setTextureArray(name, this._textureArrays[name]);
  58518. }
  58519. // Int
  58520. for (name in this._ints) {
  58521. this._effect.setInt(name, this._ints[name]);
  58522. }
  58523. // Float
  58524. for (name in this._floats) {
  58525. this._effect.setFloat(name, this._floats[name]);
  58526. }
  58527. // Floats
  58528. for (name in this._floatsArrays) {
  58529. this._effect.setArray(name, this._floatsArrays[name]);
  58530. }
  58531. // Color3
  58532. for (name in this._colors3) {
  58533. this._effect.setColor3(name, this._colors3[name]);
  58534. }
  58535. for (name in this._colors3Arrays) {
  58536. this._effect.setArray3(name, this._colors3Arrays[name]);
  58537. }
  58538. // Color4
  58539. for (name in this._colors4) {
  58540. var color = this._colors4[name];
  58541. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58542. }
  58543. // Vector2
  58544. for (name in this._vectors2) {
  58545. this._effect.setVector2(name, this._vectors2[name]);
  58546. }
  58547. // Vector3
  58548. for (name in this._vectors3) {
  58549. this._effect.setVector3(name, this._vectors3[name]);
  58550. }
  58551. // Vector4
  58552. for (name in this._vectors4) {
  58553. this._effect.setVector4(name, this._vectors4[name]);
  58554. }
  58555. // Matrix
  58556. for (name in this._matrices) {
  58557. this._effect.setMatrix(name, this._matrices[name]);
  58558. }
  58559. // Matrix 3x3
  58560. for (name in this._matrices3x3) {
  58561. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58562. }
  58563. // Matrix 2x2
  58564. for (name in this._matrices2x2) {
  58565. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58566. }
  58567. // Vector2Array
  58568. for (name in this._vectors2Arrays) {
  58569. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58570. }
  58571. // Vector3Array
  58572. for (name in this._vectors3Arrays) {
  58573. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58574. }
  58575. }
  58576. this._afterBind(mesh);
  58577. };
  58578. ShaderMaterial.prototype.getActiveTextures = function () {
  58579. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58580. for (var name in this._textures) {
  58581. activeTextures.push(this._textures[name]);
  58582. }
  58583. for (var name in this._textureArrays) {
  58584. var array = this._textureArrays[name];
  58585. for (var index = 0; index < array.length; index++) {
  58586. activeTextures.push(array[index]);
  58587. }
  58588. }
  58589. return activeTextures;
  58590. };
  58591. ShaderMaterial.prototype.hasTexture = function (texture) {
  58592. if (_super.prototype.hasTexture.call(this, texture)) {
  58593. return true;
  58594. }
  58595. for (var name in this._textures) {
  58596. if (this._textures[name] === texture) {
  58597. return true;
  58598. }
  58599. }
  58600. for (var name in this._textureArrays) {
  58601. var array = this._textureArrays[name];
  58602. for (var index = 0; index < array.length; index++) {
  58603. if (array[index] === texture) {
  58604. return true;
  58605. }
  58606. }
  58607. }
  58608. return false;
  58609. };
  58610. ShaderMaterial.prototype.clone = function (name) {
  58611. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58612. return newShaderMaterial;
  58613. };
  58614. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58615. if (forceDisposeTextures) {
  58616. var name;
  58617. for (name in this._textures) {
  58618. this._textures[name].dispose();
  58619. }
  58620. for (name in this._textureArrays) {
  58621. var array = this._textureArrays[name];
  58622. for (var index = 0; index < array.length; index++) {
  58623. array[index].dispose();
  58624. }
  58625. }
  58626. }
  58627. this._textures = {};
  58628. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58629. };
  58630. ShaderMaterial.prototype.serialize = function () {
  58631. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58632. serializationObject.customType = "BABYLON.ShaderMaterial";
  58633. serializationObject.options = this._options;
  58634. serializationObject.shaderPath = this._shaderPath;
  58635. var name;
  58636. // Texture
  58637. serializationObject.textures = {};
  58638. for (name in this._textures) {
  58639. serializationObject.textures[name] = this._textures[name].serialize();
  58640. }
  58641. // Texture arrays
  58642. serializationObject.textureArrays = {};
  58643. for (name in this._textureArrays) {
  58644. serializationObject.textureArrays[name] = [];
  58645. var array = this._textureArrays[name];
  58646. for (var index = 0; index < array.length; index++) {
  58647. serializationObject.textureArrays[name].push(array[index].serialize());
  58648. }
  58649. }
  58650. // Float
  58651. serializationObject.floats = {};
  58652. for (name in this._floats) {
  58653. serializationObject.floats[name] = this._floats[name];
  58654. }
  58655. // Float s
  58656. serializationObject.FloatArrays = {};
  58657. for (name in this._floatsArrays) {
  58658. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58659. }
  58660. // Color3
  58661. serializationObject.colors3 = {};
  58662. for (name in this._colors3) {
  58663. serializationObject.colors3[name] = this._colors3[name].asArray();
  58664. }
  58665. // Color3 array
  58666. serializationObject.colors3Arrays = {};
  58667. for (name in this._colors3Arrays) {
  58668. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58669. }
  58670. // Color4
  58671. serializationObject.colors4 = {};
  58672. for (name in this._colors4) {
  58673. serializationObject.colors4[name] = this._colors4[name].asArray();
  58674. }
  58675. // Vector2
  58676. serializationObject.vectors2 = {};
  58677. for (name in this._vectors2) {
  58678. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58679. }
  58680. // Vector3
  58681. serializationObject.vectors3 = {};
  58682. for (name in this._vectors3) {
  58683. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58684. }
  58685. // Vector4
  58686. serializationObject.vectors4 = {};
  58687. for (name in this._vectors4) {
  58688. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58689. }
  58690. // Matrix
  58691. serializationObject.matrices = {};
  58692. for (name in this._matrices) {
  58693. serializationObject.matrices[name] = this._matrices[name].asArray();
  58694. }
  58695. // Matrix 3x3
  58696. serializationObject.matrices3x3 = {};
  58697. for (name in this._matrices3x3) {
  58698. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58699. }
  58700. // Matrix 2x2
  58701. serializationObject.matrices2x2 = {};
  58702. for (name in this._matrices2x2) {
  58703. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58704. }
  58705. // Vector2Array
  58706. serializationObject.vectors2Arrays = {};
  58707. for (name in this._vectors2Arrays) {
  58708. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58709. }
  58710. // Vector3Array
  58711. serializationObject.vectors3Arrays = {};
  58712. for (name in this._vectors3Arrays) {
  58713. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58714. }
  58715. return serializationObject;
  58716. };
  58717. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58718. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58719. var name;
  58720. // Texture
  58721. for (name in source.textures) {
  58722. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58723. }
  58724. // Texture arrays
  58725. for (name in source.textureArrays) {
  58726. var array = source.textureArrays[name];
  58727. var textureArray = new Array();
  58728. for (var index = 0; index < array.length; index++) {
  58729. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58730. }
  58731. material.setTextureArray(name, textureArray);
  58732. }
  58733. // Float
  58734. for (name in source.floats) {
  58735. material.setFloat(name, source.floats[name]);
  58736. }
  58737. // Float s
  58738. for (name in source.floatsArrays) {
  58739. material.setFloats(name, source.floatsArrays[name]);
  58740. }
  58741. // Color3
  58742. for (name in source.colors3) {
  58743. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58744. }
  58745. // Color3 arrays
  58746. for (name in source.colors3Arrays) {
  58747. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58748. if (i % 3 === 0) {
  58749. arr.push([num]);
  58750. }
  58751. else {
  58752. arr[arr.length - 1].push(num);
  58753. }
  58754. return arr;
  58755. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58756. material.setColor3Array(name, colors);
  58757. }
  58758. // Color4
  58759. for (name in source.colors4) {
  58760. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58761. }
  58762. // Vector2
  58763. for (name in source.vectors2) {
  58764. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58765. }
  58766. // Vector3
  58767. for (name in source.vectors3) {
  58768. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58769. }
  58770. // Vector4
  58771. for (name in source.vectors4) {
  58772. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58773. }
  58774. // Matrix
  58775. for (name in source.matrices) {
  58776. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58777. }
  58778. // Matrix 3x3
  58779. for (name in source.matrices3x3) {
  58780. material.setMatrix3x3(name, source.matrices3x3[name]);
  58781. }
  58782. // Matrix 2x2
  58783. for (name in source.matrices2x2) {
  58784. material.setMatrix2x2(name, source.matrices2x2[name]);
  58785. }
  58786. // Vector2Array
  58787. for (name in source.vectors2Arrays) {
  58788. material.setArray2(name, source.vectors2Arrays[name]);
  58789. }
  58790. // Vector3Array
  58791. for (name in source.vectors3Arrays) {
  58792. material.setArray3(name, source.vectors3Arrays[name]);
  58793. }
  58794. return material;
  58795. };
  58796. return ShaderMaterial;
  58797. }(BABYLON.Material));
  58798. BABYLON.ShaderMaterial = ShaderMaterial;
  58799. })(BABYLON || (BABYLON = {}));
  58800. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58801. var BABYLON;
  58802. (function (BABYLON) {
  58803. var GroundMesh = /** @class */ (function (_super) {
  58804. __extends(GroundMesh, _super);
  58805. function GroundMesh(name, scene) {
  58806. var _this = _super.call(this, name, scene) || this;
  58807. _this.generateOctree = false;
  58808. return _this;
  58809. }
  58810. GroundMesh.prototype.getClassName = function () {
  58811. return "GroundMesh";
  58812. };
  58813. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58814. get: function () {
  58815. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58816. },
  58817. enumerable: true,
  58818. configurable: true
  58819. });
  58820. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58821. get: function () {
  58822. return this._subdivisionsX;
  58823. },
  58824. enumerable: true,
  58825. configurable: true
  58826. });
  58827. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58828. get: function () {
  58829. return this._subdivisionsY;
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58835. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58836. this._subdivisionsX = chunksCount;
  58837. this._subdivisionsY = chunksCount;
  58838. this.subdivide(chunksCount);
  58839. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58840. };
  58841. /**
  58842. * Returns a height (y) value in the Worl system :
  58843. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58844. * Returns the ground y position if (x, z) are outside the ground surface.
  58845. */
  58846. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58847. var world = this.getWorldMatrix();
  58848. var invMat = BABYLON.Tmp.Matrix[5];
  58849. world.invertToRef(invMat);
  58850. var tmpVect = BABYLON.Tmp.Vector3[8];
  58851. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58852. x = tmpVect.x;
  58853. z = tmpVect.z;
  58854. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58855. return this.position.y;
  58856. }
  58857. if (!this._heightQuads || this._heightQuads.length == 0) {
  58858. this._initHeightQuads();
  58859. this._computeHeightQuads();
  58860. }
  58861. var facet = this._getFacetAt(x, z);
  58862. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58863. // return y in the World system
  58864. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58865. return tmpVect.y;
  58866. };
  58867. /**
  58868. * Returns a normalized vector (Vector3) orthogonal to the ground
  58869. * at the ground coordinates (x, z) expressed in the World system.
  58870. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58871. */
  58872. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58873. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58874. this.getNormalAtCoordinatesToRef(x, z, normal);
  58875. return normal;
  58876. };
  58877. /**
  58878. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58879. * at the ground coordinates (x, z) expressed in the World system.
  58880. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58881. * Returns the GroundMesh.
  58882. */
  58883. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58884. var world = this.getWorldMatrix();
  58885. var tmpMat = BABYLON.Tmp.Matrix[5];
  58886. world.invertToRef(tmpMat);
  58887. var tmpVect = BABYLON.Tmp.Vector3[8];
  58888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58889. x = tmpVect.x;
  58890. z = tmpVect.z;
  58891. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58892. return this;
  58893. }
  58894. if (!this._heightQuads || this._heightQuads.length == 0) {
  58895. this._initHeightQuads();
  58896. this._computeHeightQuads();
  58897. }
  58898. var facet = this._getFacetAt(x, z);
  58899. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58900. return this;
  58901. };
  58902. /**
  58903. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58904. * if the ground has been updated.
  58905. * This can be used in the render loop.
  58906. * Returns the GroundMesh.
  58907. */
  58908. GroundMesh.prototype.updateCoordinateHeights = function () {
  58909. if (!this._heightQuads || this._heightQuads.length == 0) {
  58910. this._initHeightQuads();
  58911. }
  58912. this._computeHeightQuads();
  58913. return this;
  58914. };
  58915. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58916. GroundMesh.prototype._getFacetAt = function (x, z) {
  58917. // retrieve col and row from x, z coordinates in the ground local system
  58918. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58919. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58920. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58921. var facet;
  58922. if (z < quad.slope.x * x + quad.slope.y) {
  58923. facet = quad.facet1;
  58924. }
  58925. else {
  58926. facet = quad.facet2;
  58927. }
  58928. return facet;
  58929. };
  58930. // Creates and populates the heightMap array with "facet" elements :
  58931. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58932. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58933. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58934. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58935. // Returns the GroundMesh.
  58936. GroundMesh.prototype._initHeightQuads = function () {
  58937. var subdivisionsX = this._subdivisionsX;
  58938. var subdivisionsY = this._subdivisionsY;
  58939. this._heightQuads = new Array();
  58940. for (var row = 0; row < subdivisionsY; row++) {
  58941. for (var col = 0; col < subdivisionsX; col++) {
  58942. 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) };
  58943. this._heightQuads[row * subdivisionsX + col] = quad;
  58944. }
  58945. }
  58946. return this;
  58947. };
  58948. // Compute each quad element values and update the the heightMap array :
  58949. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58950. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58951. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58952. // Returns the GroundMesh.
  58953. GroundMesh.prototype._computeHeightQuads = function () {
  58954. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58955. if (!positions) {
  58956. return this;
  58957. }
  58958. var v1 = BABYLON.Tmp.Vector3[3];
  58959. var v2 = BABYLON.Tmp.Vector3[2];
  58960. var v3 = BABYLON.Tmp.Vector3[1];
  58961. var v4 = BABYLON.Tmp.Vector3[0];
  58962. var v1v2 = BABYLON.Tmp.Vector3[4];
  58963. var v1v3 = BABYLON.Tmp.Vector3[5];
  58964. var v1v4 = BABYLON.Tmp.Vector3[6];
  58965. var norm1 = BABYLON.Tmp.Vector3[7];
  58966. var norm2 = BABYLON.Tmp.Vector3[8];
  58967. var i = 0;
  58968. var j = 0;
  58969. var k = 0;
  58970. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58971. var h = 0;
  58972. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58973. var d2 = 0;
  58974. var subdivisionsX = this._subdivisionsX;
  58975. var subdivisionsY = this._subdivisionsY;
  58976. for (var row = 0; row < subdivisionsY; row++) {
  58977. for (var col = 0; col < subdivisionsX; col++) {
  58978. i = col * 3;
  58979. j = row * (subdivisionsX + 1) * 3;
  58980. k = (row + 1) * (subdivisionsX + 1) * 3;
  58981. v1.x = positions[j + i];
  58982. v1.y = positions[j + i + 1];
  58983. v1.z = positions[j + i + 2];
  58984. v2.x = positions[j + i + 3];
  58985. v2.y = positions[j + i + 4];
  58986. v2.z = positions[j + i + 5];
  58987. v3.x = positions[k + i];
  58988. v3.y = positions[k + i + 1];
  58989. v3.z = positions[k + i + 2];
  58990. v4.x = positions[k + i + 3];
  58991. v4.y = positions[k + i + 4];
  58992. v4.z = positions[k + i + 5];
  58993. // 2D slope V1V4
  58994. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58995. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58996. // facet equations :
  58997. // we compute each facet normal vector
  58998. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58999. // we compute the value d by applying the equation to v1 which belongs to the plane
  59000. // then we store the facet equation in a Vector4
  59001. v2.subtractToRef(v1, v1v2);
  59002. v3.subtractToRef(v1, v1v3);
  59003. v4.subtractToRef(v1, v1v4);
  59004. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59005. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59006. norm1.normalize();
  59007. norm2.normalize();
  59008. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59009. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59010. var quad = this._heightQuads[row * subdivisionsX + col];
  59011. quad.slope.copyFromFloats(cd, h);
  59012. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59013. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59014. }
  59015. }
  59016. return this;
  59017. };
  59018. GroundMesh.prototype.serialize = function (serializationObject) {
  59019. _super.prototype.serialize.call(this, serializationObject);
  59020. serializationObject.subdivisionsX = this._subdivisionsX;
  59021. serializationObject.subdivisionsY = this._subdivisionsY;
  59022. serializationObject.minX = this._minX;
  59023. serializationObject.maxX = this._maxX;
  59024. serializationObject.minZ = this._minZ;
  59025. serializationObject.maxZ = this._maxZ;
  59026. serializationObject.width = this._width;
  59027. serializationObject.height = this._height;
  59028. };
  59029. GroundMesh.Parse = function (parsedMesh, scene) {
  59030. var result = new GroundMesh(parsedMesh.name, scene);
  59031. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59032. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59033. result._minX = parsedMesh.minX;
  59034. result._maxX = parsedMesh.maxX;
  59035. result._minZ = parsedMesh.minZ;
  59036. result._maxZ = parsedMesh.maxZ;
  59037. result._width = parsedMesh.width;
  59038. result._height = parsedMesh.height;
  59039. return result;
  59040. };
  59041. return GroundMesh;
  59042. }(BABYLON.Mesh));
  59043. BABYLON.GroundMesh = GroundMesh;
  59044. })(BABYLON || (BABYLON = {}));
  59045. //# sourceMappingURL=babylon.groundMesh.js.map
  59046. var BABYLON;
  59047. (function (BABYLON) {
  59048. /**
  59049. * Creates an instance based on a source mesh.
  59050. */
  59051. var InstancedMesh = /** @class */ (function (_super) {
  59052. __extends(InstancedMesh, _super);
  59053. function InstancedMesh(name, source) {
  59054. var _this = _super.call(this, name, source.getScene()) || this;
  59055. source.instances.push(_this);
  59056. _this._sourceMesh = source;
  59057. _this.position.copyFrom(source.position);
  59058. _this.rotation.copyFrom(source.rotation);
  59059. _this.scaling.copyFrom(source.scaling);
  59060. if (source.rotationQuaternion) {
  59061. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59062. }
  59063. _this.infiniteDistance = source.infiniteDistance;
  59064. _this.setPivotMatrix(source.getPivotMatrix());
  59065. _this.refreshBoundingInfo();
  59066. _this._syncSubMeshes();
  59067. return _this;
  59068. }
  59069. /**
  59070. * Returns the string "InstancedMesh".
  59071. */
  59072. InstancedMesh.prototype.getClassName = function () {
  59073. return "InstancedMesh";
  59074. };
  59075. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59076. // Methods
  59077. get: function () {
  59078. return this._sourceMesh.receiveShadows;
  59079. },
  59080. enumerable: true,
  59081. configurable: true
  59082. });
  59083. Object.defineProperty(InstancedMesh.prototype, "material", {
  59084. get: function () {
  59085. return this._sourceMesh.material;
  59086. },
  59087. enumerable: true,
  59088. configurable: true
  59089. });
  59090. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59091. get: function () {
  59092. return this._sourceMesh.visibility;
  59093. },
  59094. enumerable: true,
  59095. configurable: true
  59096. });
  59097. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59098. get: function () {
  59099. return this._sourceMesh.skeleton;
  59100. },
  59101. enumerable: true,
  59102. configurable: true
  59103. });
  59104. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59105. get: function () {
  59106. return this._sourceMesh.renderingGroupId;
  59107. },
  59108. set: function (value) {
  59109. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59110. return;
  59111. }
  59112. //no-op with warning
  59113. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59114. },
  59115. enumerable: true,
  59116. configurable: true
  59117. });
  59118. /**
  59119. * Returns the total number of vertices (integer).
  59120. */
  59121. InstancedMesh.prototype.getTotalVertices = function () {
  59122. return this._sourceMesh.getTotalVertices();
  59123. };
  59124. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59125. get: function () {
  59126. return this._sourceMesh;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. /**
  59132. * Is this node ready to be used/rendered
  59133. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59134. * @return {boolean} is it ready
  59135. */
  59136. InstancedMesh.prototype.isReady = function (completeCheck) {
  59137. if (completeCheck === void 0) { completeCheck = false; }
  59138. return this._sourceMesh.isReady(completeCheck, true);
  59139. };
  59140. /**
  59141. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59142. */
  59143. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59144. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59145. };
  59146. /**
  59147. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59148. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59149. * The `data` are either a numeric array either a Float32Array.
  59150. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59151. * 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).
  59152. * Note that a new underlying VertexBuffer object is created each call.
  59153. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59154. *
  59155. * Possible `kind` values :
  59156. * - BABYLON.VertexBuffer.PositionKind
  59157. * - BABYLON.VertexBuffer.UVKind
  59158. * - BABYLON.VertexBuffer.UV2Kind
  59159. * - BABYLON.VertexBuffer.UV3Kind
  59160. * - BABYLON.VertexBuffer.UV4Kind
  59161. * - BABYLON.VertexBuffer.UV5Kind
  59162. * - BABYLON.VertexBuffer.UV6Kind
  59163. * - BABYLON.VertexBuffer.ColorKind
  59164. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59165. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59166. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59167. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59168. *
  59169. * Returns the Mesh.
  59170. */
  59171. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59172. if (this.sourceMesh) {
  59173. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59174. }
  59175. return this.sourceMesh;
  59176. };
  59177. /**
  59178. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59179. * If the mesh has no geometry, it is simply returned as it is.
  59180. * The `data` are either a numeric array either a Float32Array.
  59181. * No new underlying VertexBuffer object is created.
  59182. * 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.
  59183. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59184. *
  59185. * Possible `kind` values :
  59186. * - BABYLON.VertexBuffer.PositionKind
  59187. * - BABYLON.VertexBuffer.UVKind
  59188. * - BABYLON.VertexBuffer.UV2Kind
  59189. * - BABYLON.VertexBuffer.UV3Kind
  59190. * - BABYLON.VertexBuffer.UV4Kind
  59191. * - BABYLON.VertexBuffer.UV5Kind
  59192. * - BABYLON.VertexBuffer.UV6Kind
  59193. * - BABYLON.VertexBuffer.ColorKind
  59194. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59195. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59196. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59197. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59198. *
  59199. * Returns the Mesh.
  59200. */
  59201. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59202. if (this.sourceMesh) {
  59203. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59204. }
  59205. return this.sourceMesh;
  59206. };
  59207. /**
  59208. * Sets the mesh indices.
  59209. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59210. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59211. * This method creates a new index buffer each call.
  59212. * Returns the Mesh.
  59213. */
  59214. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59215. if (totalVertices === void 0) { totalVertices = null; }
  59216. if (this.sourceMesh) {
  59217. this.sourceMesh.setIndices(indices, totalVertices);
  59218. }
  59219. return this.sourceMesh;
  59220. };
  59221. /**
  59222. * Boolean : True if the mesh owns the requested kind of data.
  59223. */
  59224. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59225. return this._sourceMesh.isVerticesDataPresent(kind);
  59226. };
  59227. /**
  59228. * Returns an array of indices (IndicesArray).
  59229. */
  59230. InstancedMesh.prototype.getIndices = function () {
  59231. return this._sourceMesh.getIndices();
  59232. };
  59233. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59234. get: function () {
  59235. return this._sourceMesh._positions;
  59236. },
  59237. enumerable: true,
  59238. configurable: true
  59239. });
  59240. /**
  59241. * Sets a new updated BoundingInfo to the mesh.
  59242. * Returns the mesh.
  59243. */
  59244. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59245. var meshBB = this._sourceMesh.getBoundingInfo();
  59246. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59247. this._updateBoundingInfo();
  59248. return this;
  59249. };
  59250. InstancedMesh.prototype._preActivate = function () {
  59251. if (this._currentLOD) {
  59252. this._currentLOD._preActivate();
  59253. }
  59254. return this;
  59255. };
  59256. InstancedMesh.prototype._activate = function (renderId) {
  59257. if (this._currentLOD) {
  59258. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59259. }
  59260. return this;
  59261. };
  59262. /**
  59263. * Returns the current associated LOD AbstractMesh.
  59264. */
  59265. InstancedMesh.prototype.getLOD = function (camera) {
  59266. if (!camera) {
  59267. return this;
  59268. }
  59269. var boundingInfo = this.getBoundingInfo();
  59270. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59271. if (this._currentLOD === this.sourceMesh) {
  59272. return this;
  59273. }
  59274. return this._currentLOD;
  59275. };
  59276. InstancedMesh.prototype._syncSubMeshes = function () {
  59277. this.releaseSubMeshes();
  59278. if (this._sourceMesh.subMeshes) {
  59279. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59280. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59281. }
  59282. }
  59283. return this;
  59284. };
  59285. InstancedMesh.prototype._generatePointsArray = function () {
  59286. return this._sourceMesh._generatePointsArray();
  59287. };
  59288. /**
  59289. * Creates a new InstancedMesh from the current mesh.
  59290. * - name (string) : the cloned mesh name
  59291. * - newParent (optional Node) : the optional Node to parent the clone to.
  59292. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59293. *
  59294. * Returns the clone.
  59295. */
  59296. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59297. var result = this._sourceMesh.createInstance(name);
  59298. // Deep copy
  59299. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59300. // Bounding info
  59301. this.refreshBoundingInfo();
  59302. // Parent
  59303. if (newParent) {
  59304. result.parent = newParent;
  59305. }
  59306. if (!doNotCloneChildren) {
  59307. // Children
  59308. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59309. var mesh = this.getScene().meshes[index];
  59310. if (mesh.parent === this) {
  59311. mesh.clone(mesh.name, result);
  59312. }
  59313. }
  59314. }
  59315. result.computeWorldMatrix(true);
  59316. return result;
  59317. };
  59318. /**
  59319. * Disposes the InstancedMesh.
  59320. * Returns nothing.
  59321. */
  59322. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59323. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59324. // Remove from mesh
  59325. var index = this._sourceMesh.instances.indexOf(this);
  59326. this._sourceMesh.instances.splice(index, 1);
  59327. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59328. };
  59329. return InstancedMesh;
  59330. }(BABYLON.AbstractMesh));
  59331. BABYLON.InstancedMesh = InstancedMesh;
  59332. })(BABYLON || (BABYLON = {}));
  59333. //# sourceMappingURL=babylon.instancedMesh.js.map
  59334. var BABYLON;
  59335. (function (BABYLON) {
  59336. var LinesMesh = /** @class */ (function (_super) {
  59337. __extends(LinesMesh, _super);
  59338. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59339. if (scene === void 0) { scene = null; }
  59340. if (parent === void 0) { parent = null; }
  59341. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59342. _this.useVertexColor = useVertexColor;
  59343. _this.useVertexAlpha = useVertexAlpha;
  59344. _this.color = new BABYLON.Color3(1, 1, 1);
  59345. _this.alpha = 1;
  59346. if (source) {
  59347. _this.color = source.color.clone();
  59348. _this.alpha = source.alpha;
  59349. _this.useVertexColor = source.useVertexColor;
  59350. _this.useVertexAlpha = source.useVertexAlpha;
  59351. }
  59352. _this._intersectionThreshold = 0.1;
  59353. var defines = [];
  59354. var options = {
  59355. attributes: [BABYLON.VertexBuffer.PositionKind],
  59356. uniforms: ["world", "viewProjection"],
  59357. needAlphaBlending: true,
  59358. defines: defines
  59359. };
  59360. if (useVertexAlpha === false) {
  59361. options.needAlphaBlending = false;
  59362. }
  59363. if (!useVertexColor) {
  59364. options.uniforms.push("color");
  59365. }
  59366. else {
  59367. options.defines.push("#define VERTEXCOLOR");
  59368. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59369. }
  59370. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59371. return _this;
  59372. }
  59373. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59374. /**
  59375. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59376. * This margin is expressed in world space coordinates, so its value may vary.
  59377. * Default value is 0.1
  59378. * @returns the intersection Threshold value.
  59379. */
  59380. get: function () {
  59381. return this._intersectionThreshold;
  59382. },
  59383. /**
  59384. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59385. * This margin is expressed in world space coordinates, so its value may vary.
  59386. * @param value the new threshold to apply
  59387. */
  59388. set: function (value) {
  59389. if (this._intersectionThreshold === value) {
  59390. return;
  59391. }
  59392. this._intersectionThreshold = value;
  59393. if (this.geometry) {
  59394. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59395. }
  59396. },
  59397. enumerable: true,
  59398. configurable: true
  59399. });
  59400. /**
  59401. * Returns the string "LineMesh"
  59402. */
  59403. LinesMesh.prototype.getClassName = function () {
  59404. return "LinesMesh";
  59405. };
  59406. Object.defineProperty(LinesMesh.prototype, "material", {
  59407. get: function () {
  59408. return this._colorShader;
  59409. },
  59410. set: function (value) {
  59411. // Do nothing
  59412. },
  59413. enumerable: true,
  59414. configurable: true
  59415. });
  59416. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59417. get: function () {
  59418. return false;
  59419. },
  59420. enumerable: true,
  59421. configurable: true
  59422. });
  59423. LinesMesh.prototype.createInstance = function (name) {
  59424. throw new Error("LinesMeshes do not support createInstance.");
  59425. };
  59426. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59427. if (!this._geometry) {
  59428. return this;
  59429. }
  59430. // VBOs
  59431. this._geometry._bind(this._colorShader.getEffect());
  59432. // Color
  59433. if (!this.useVertexColor) {
  59434. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59435. }
  59436. return this;
  59437. };
  59438. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59439. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59440. return this;
  59441. }
  59442. var engine = this.getScene().getEngine();
  59443. // Draw order
  59444. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59445. return this;
  59446. };
  59447. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59448. this._colorShader.dispose();
  59449. _super.prototype.dispose.call(this, doNotRecurse);
  59450. };
  59451. /**
  59452. * Returns a new LineMesh object cloned from the current one.
  59453. */
  59454. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59455. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59456. };
  59457. return LinesMesh;
  59458. }(BABYLON.Mesh));
  59459. BABYLON.LinesMesh = LinesMesh;
  59460. })(BABYLON || (BABYLON = {}));
  59461. //# sourceMappingURL=babylon.linesMesh.js.map
  59462. var BABYLON;
  59463. (function (BABYLON) {
  59464. /**
  59465. * Class containing static functions to help procedurally build meshes
  59466. */
  59467. var MeshBuilder = /** @class */ (function () {
  59468. function MeshBuilder() {
  59469. }
  59470. MeshBuilder.updateSideOrientation = function (orientation) {
  59471. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59472. return BABYLON.Mesh.DOUBLESIDE;
  59473. }
  59474. if (orientation === undefined || orientation === null) {
  59475. return BABYLON.Mesh.FRONTSIDE;
  59476. }
  59477. return orientation;
  59478. };
  59479. /**
  59480. * Creates a box mesh
  59481. * * The parameter `size` sets the size (float) of each box side (default 1)
  59482. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59483. * * 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)
  59484. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59485. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59486. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59487. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59488. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59489. * @param name defines the name of the mesh
  59490. * @param options defines the options used to create the mesh
  59491. * @param scene defines the hosting scene
  59492. * @returns the box mesh
  59493. */
  59494. MeshBuilder.CreateBox = function (name, options, scene) {
  59495. if (scene === void 0) { scene = null; }
  59496. var box = new BABYLON.Mesh(name, scene);
  59497. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59498. box._originalBuilderSideOrientation = options.sideOrientation;
  59499. var vertexData = BABYLON.VertexData.CreateBox(options);
  59500. vertexData.applyToMesh(box, options.updatable);
  59501. return box;
  59502. };
  59503. /**
  59504. * Creates a sphere mesh
  59505. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59506. * * 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`)
  59507. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59508. * * 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
  59509. * * 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)
  59510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59511. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59512. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59513. * @param name defines the name of the mesh
  59514. * @param options defines the options used to create the mesh
  59515. * @param scene defines the hosting scene
  59516. * @returns the sphere mesh
  59517. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59518. */
  59519. MeshBuilder.CreateSphere = function (name, options, scene) {
  59520. var sphere = new BABYLON.Mesh(name, scene);
  59521. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59522. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59523. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59524. vertexData.applyToMesh(sphere, options.updatable);
  59525. return sphere;
  59526. };
  59527. /**
  59528. * Creates a plane polygonal mesh. By default, this is a disc
  59529. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59530. * * 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
  59531. * * 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
  59532. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59533. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59534. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59535. * @param name defines the name of the mesh
  59536. * @param options defines the options used to create the mesh
  59537. * @param scene defines the hosting scene
  59538. * @returns the plane polygonal mesh
  59539. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59540. */
  59541. MeshBuilder.CreateDisc = function (name, options, scene) {
  59542. if (scene === void 0) { scene = null; }
  59543. var disc = new BABYLON.Mesh(name, scene);
  59544. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59545. disc._originalBuilderSideOrientation = options.sideOrientation;
  59546. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59547. vertexData.applyToMesh(disc, options.updatable);
  59548. return disc;
  59549. };
  59550. /**
  59551. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59552. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59553. * * 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`)
  59554. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59555. * * 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
  59556. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59557. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59558. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59559. * @param name defines the name of the mesh
  59560. * @param options defines the options used to create the mesh
  59561. * @param scene defines the hosting scene
  59562. * @returns the icosahedron mesh
  59563. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59564. */
  59565. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59566. var sphere = new BABYLON.Mesh(name, scene);
  59567. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59568. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59569. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59570. vertexData.applyToMesh(sphere, options.updatable);
  59571. return sphere;
  59572. };
  59573. ;
  59574. /**
  59575. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59576. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59577. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59578. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59579. * * 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
  59580. * * 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
  59581. * * 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
  59582. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59583. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59584. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59585. * * 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
  59586. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59587. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  59588. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59589. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59590. * @param name defines the name of the mesh
  59591. * @param options defines the options used to create the mesh
  59592. * @param scene defines the hosting scene
  59593. * @returns the ribbon mesh
  59594. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59595. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59596. */
  59597. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59598. if (scene === void 0) { scene = null; }
  59599. var pathArray = options.pathArray;
  59600. var closeArray = options.closeArray;
  59601. var closePath = options.closePath;
  59602. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59603. var instance = options.instance;
  59604. var updatable = options.updatable;
  59605. if (instance) { // existing ribbon instance update
  59606. // positionFunction : ribbon case
  59607. // only pathArray and sideOrientation parameters are taken into account for positions update
  59608. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59609. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59610. var positionFunction = function (positions) {
  59611. var minlg = pathArray[0].length;
  59612. var i = 0;
  59613. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59614. for (var si = 1; si <= ns; si++) {
  59615. for (var p = 0; p < pathArray.length; p++) {
  59616. var path = pathArray[p];
  59617. var l = path.length;
  59618. minlg = (minlg < l) ? minlg : l;
  59619. var j = 0;
  59620. while (j < minlg) {
  59621. positions[i] = path[j].x;
  59622. positions[i + 1] = path[j].y;
  59623. positions[i + 2] = path[j].z;
  59624. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59625. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59626. }
  59627. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59628. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59629. }
  59630. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59631. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59632. }
  59633. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59634. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59635. }
  59636. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59637. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59638. }
  59639. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59640. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59641. }
  59642. j++;
  59643. i += 3;
  59644. }
  59645. if (instance._closePath) {
  59646. positions[i] = path[0].x;
  59647. positions[i + 1] = path[0].y;
  59648. positions[i + 2] = path[0].z;
  59649. i += 3;
  59650. }
  59651. }
  59652. }
  59653. };
  59654. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59655. positionFunction(positions);
  59656. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59657. instance._boundingInfo.update(instance._worldMatrix);
  59658. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59659. if (options.colors) {
  59660. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59661. for (var c = 0; c < options.colors.length; c++) {
  59662. colors[c * 4] = options.colors[c].r;
  59663. colors[c * 4 + 1] = options.colors[c].g;
  59664. colors[c * 4 + 2] = options.colors[c].b;
  59665. colors[c * 4 + 3] = options.colors[c].a;
  59666. }
  59667. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59668. }
  59669. if (options.uvs) {
  59670. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59671. for (var i = 0; i < options.uvs.length; i++) {
  59672. uvs[i * 2] = options.uvs[i].x;
  59673. uvs[i * 2 + 1] = options.uvs[i].y;
  59674. }
  59675. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59676. }
  59677. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59678. var indices = instance.getIndices();
  59679. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59680. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59681. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59682. if (instance._closePath) {
  59683. var indexFirst = 0;
  59684. var indexLast = 0;
  59685. for (var p = 0; p < pathArray.length; p++) {
  59686. indexFirst = instance._idx[p] * 3;
  59687. if (p + 1 < pathArray.length) {
  59688. indexLast = (instance._idx[p + 1] - 1) * 3;
  59689. }
  59690. else {
  59691. indexLast = normals.length - 3;
  59692. }
  59693. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59694. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59695. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59696. normals[indexLast] = normals[indexFirst];
  59697. normals[indexLast + 1] = normals[indexFirst + 1];
  59698. normals[indexLast + 2] = normals[indexFirst + 2];
  59699. }
  59700. }
  59701. if (!(instance.areNormalsFrozen)) {
  59702. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59703. }
  59704. }
  59705. return instance;
  59706. }
  59707. else { // new ribbon creation
  59708. var ribbon = new BABYLON.Mesh(name, scene);
  59709. ribbon._originalBuilderSideOrientation = sideOrientation;
  59710. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59711. if (closePath) {
  59712. ribbon._idx = vertexData._idx;
  59713. }
  59714. ribbon._closePath = closePath;
  59715. ribbon._closeArray = closeArray;
  59716. vertexData.applyToMesh(ribbon, updatable);
  59717. return ribbon;
  59718. }
  59719. };
  59720. /**
  59721. * Creates a cylinder or a cone mesh
  59722. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59723. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59724. * * 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.
  59725. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59726. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59727. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59728. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59729. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59730. * * 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).
  59731. * * 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
  59732. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59733. * * 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
  59734. * * 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.
  59735. * * If `enclose` is false, a ring surface is one element.
  59736. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59737. * * 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
  59738. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59739. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59740. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59741. * @param name defines the name of the mesh
  59742. * @param options defines the options used to create the mesh
  59743. * @param scene defines the hosting scene
  59744. * @returns the cylinder mesh
  59745. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59746. */
  59747. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59748. var cylinder = new BABYLON.Mesh(name, scene);
  59749. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59750. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59751. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59752. vertexData.applyToMesh(cylinder, options.updatable);
  59753. return cylinder;
  59754. };
  59755. /**
  59756. * Creates a torus mesh
  59757. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59758. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59759. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59760. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59761. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59762. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59763. * @param name defines the name of the mesh
  59764. * @param options defines the options used to create the mesh
  59765. * @param scene defines the hosting scene
  59766. * @returns the torus mesh
  59767. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59768. */
  59769. MeshBuilder.CreateTorus = function (name, options, scene) {
  59770. var torus = new BABYLON.Mesh(name, scene);
  59771. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59772. torus._originalBuilderSideOrientation = options.sideOrientation;
  59773. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59774. vertexData.applyToMesh(torus, options.updatable);
  59775. return torus;
  59776. };
  59777. /**
  59778. * Creates a torus knot mesh
  59779. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59780. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59781. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59782. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59783. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59784. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59785. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59786. * @param name defines the name of the mesh
  59787. * @param options defines the options used to create the mesh
  59788. * @param scene defines the hosting scene
  59789. * @returns the torus knot mesh
  59790. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59791. */
  59792. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59793. var torusKnot = new BABYLON.Mesh(name, scene);
  59794. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59795. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59796. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59797. vertexData.applyToMesh(torusKnot, options.updatable);
  59798. return torusKnot;
  59799. };
  59800. /**
  59801. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59802. * * 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
  59803. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59804. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59805. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59806. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59807. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59808. * * 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
  59809. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59810. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59811. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59812. * @param name defines the name of the new line system
  59813. * @param options defines the options used to create the line system
  59814. * @param scene defines the hosting scene
  59815. * @returns a new line system mesh
  59816. */
  59817. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59818. var instance = options.instance;
  59819. var lines = options.lines;
  59820. var colors = options.colors;
  59821. if (instance) { // lines update
  59822. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59823. var vertexColor;
  59824. var lineColors;
  59825. if (colors) {
  59826. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59827. }
  59828. var i = 0;
  59829. var c = 0;
  59830. for (var l = 0; l < lines.length; l++) {
  59831. var points = lines[l];
  59832. for (var p = 0; p < points.length; p++) {
  59833. positions[i] = points[p].x;
  59834. positions[i + 1] = points[p].y;
  59835. positions[i + 2] = points[p].z;
  59836. if (colors && vertexColor) {
  59837. lineColors = colors[l];
  59838. vertexColor[c] = lineColors[p].r;
  59839. vertexColor[c + 1] = lineColors[p].g;
  59840. vertexColor[c + 2] = lineColors[p].b;
  59841. vertexColor[c + 3] = lineColors[p].a;
  59842. c += 4;
  59843. }
  59844. i += 3;
  59845. }
  59846. }
  59847. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59848. if (colors && vertexColor) {
  59849. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59850. }
  59851. return instance;
  59852. }
  59853. // line system creation
  59854. var useVertexColor = (colors) ? true : false;
  59855. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59856. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59857. vertexData.applyToMesh(lineSystem, options.updatable);
  59858. return lineSystem;
  59859. };
  59860. /**
  59861. * Creates a line mesh
  59862. * 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
  59863. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59864. * * The parameter `points` is an array successive Vector3
  59865. * * 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
  59866. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59867. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59868. * * When updating an instance, remember that only point positions can change, not the number of points
  59869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59870. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59871. * @param name defines the name of the new line system
  59872. * @param options defines the options used to create the line system
  59873. * @param scene defines the hosting scene
  59874. * @returns a new line mesh
  59875. */
  59876. MeshBuilder.CreateLines = function (name, options, scene) {
  59877. if (scene === void 0) { scene = null; }
  59878. var colors = (options.colors) ? [options.colors] : null;
  59879. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59880. return lines;
  59881. };
  59882. /**
  59883. * Creates a dashed line mesh
  59884. * * 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
  59885. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59886. * * The parameter `points` is an array successive Vector3
  59887. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59888. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59889. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59890. * * 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
  59891. * * When updating an instance, remember that only point positions can change, not the number of points
  59892. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59893. * @param name defines the name of the mesh
  59894. * @param options defines the options used to create the mesh
  59895. * @param scene defines the hosting scene
  59896. * @returns the dashed line mesh
  59897. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59898. */
  59899. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59900. if (scene === void 0) { scene = null; }
  59901. var points = options.points;
  59902. var instance = options.instance;
  59903. var gapSize = options.gapSize || 1;
  59904. var dashSize = options.dashSize || 3;
  59905. if (instance) { // dashed lines update
  59906. var positionFunction = function (positions) {
  59907. var curvect = BABYLON.Vector3.Zero();
  59908. var nbSeg = positions.length / 6;
  59909. var lg = 0;
  59910. var nb = 0;
  59911. var shft = 0;
  59912. var dashshft = 0;
  59913. var curshft = 0;
  59914. var p = 0;
  59915. var i = 0;
  59916. var j = 0;
  59917. for (i = 0; i < points.length - 1; i++) {
  59918. points[i + 1].subtractToRef(points[i], curvect);
  59919. lg += curvect.length();
  59920. }
  59921. shft = lg / nbSeg;
  59922. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59923. for (i = 0; i < points.length - 1; i++) {
  59924. points[i + 1].subtractToRef(points[i], curvect);
  59925. nb = Math.floor(curvect.length() / shft);
  59926. curvect.normalize();
  59927. j = 0;
  59928. while (j < nb && p < positions.length) {
  59929. curshft = shft * j;
  59930. positions[p] = points[i].x + curshft * curvect.x;
  59931. positions[p + 1] = points[i].y + curshft * curvect.y;
  59932. positions[p + 2] = points[i].z + curshft * curvect.z;
  59933. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59934. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59935. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59936. p += 6;
  59937. j++;
  59938. }
  59939. }
  59940. while (p < positions.length) {
  59941. positions[p] = points[i].x;
  59942. positions[p + 1] = points[i].y;
  59943. positions[p + 2] = points[i].z;
  59944. p += 3;
  59945. }
  59946. };
  59947. instance.updateMeshPositions(positionFunction, false);
  59948. return instance;
  59949. }
  59950. // dashed lines creation
  59951. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59952. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59953. vertexData.applyToMesh(dashedLines, options.updatable);
  59954. dashedLines.dashSize = dashSize;
  59955. dashedLines.gapSize = gapSize;
  59956. return dashedLines;
  59957. };
  59958. /**
  59959. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59960. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  59961. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59962. * * 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.
  59963. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  59964. * * 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
  59965. * * 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
  59966. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59967. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59968. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59969. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59970. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59971. * @param name defines the name of the mesh
  59972. * @param options defines the options used to create the mesh
  59973. * @param scene defines the hosting scene
  59974. * @returns the extruded shape mesh
  59975. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59976. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59977. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59978. */
  59979. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59980. if (scene === void 0) { scene = null; }
  59981. var path = options.path;
  59982. var shape = options.shape;
  59983. var scale = options.scale || 1;
  59984. var rotation = options.rotation || 0;
  59985. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59986. var updatable = options.updatable;
  59987. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59988. var instance = options.instance || null;
  59989. var invertUV = options.invertUV || false;
  59990. 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);
  59991. };
  59992. /**
  59993. * Creates an custom extruded shape mesh.
  59994. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59995. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  59996. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59997. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  59998. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59999. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60000. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60001. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60002. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60003. * * 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
  60004. * * 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
  60005. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60006. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60007. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60008. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60009. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60010. * @param name defines the name of the mesh
  60011. * @param options defines the options used to create the mesh
  60012. * @param scene defines the hosting scene
  60013. * @returns the custom extruded shape mesh
  60014. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60015. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60016. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60017. */
  60018. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60019. var path = options.path;
  60020. var shape = options.shape;
  60021. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60022. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60023. var ribbonCloseArray = options.ribbonCloseArray || false;
  60024. var ribbonClosePath = options.ribbonClosePath || false;
  60025. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60026. var updatable = options.updatable;
  60027. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60028. var instance = options.instance;
  60029. var invertUV = options.invertUV || false;
  60030. 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);
  60031. };
  60032. /**
  60033. * Creates lathe mesh.
  60034. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60035. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60036. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60037. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60038. * * 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
  60039. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60040. * * 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
  60041. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60042. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60043. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60044. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60045. * @param name defines the name of the mesh
  60046. * @param options defines the options used to create the mesh
  60047. * @param scene defines the hosting scene
  60048. * @returns the lathe mesh
  60049. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60050. */
  60051. MeshBuilder.CreateLathe = function (name, options, scene) {
  60052. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60053. var closed = (options.closed === undefined) ? true : options.closed;
  60054. var shape = options.shape;
  60055. var radius = options.radius || 1;
  60056. var tessellation = options.tessellation || 64;
  60057. var updatable = options.updatable;
  60058. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60059. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60060. var pi2 = Math.PI * 2;
  60061. var paths = new Array();
  60062. var invertUV = options.invertUV || false;
  60063. var i = 0;
  60064. var p = 0;
  60065. var step = pi2 / tessellation * arc;
  60066. var rotated;
  60067. var path = new Array();
  60068. ;
  60069. for (i = 0; i <= tessellation; i++) {
  60070. var path = [];
  60071. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60072. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60073. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60074. }
  60075. for (p = 0; p < shape.length; p++) {
  60076. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60077. path.push(rotated);
  60078. }
  60079. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60080. 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));
  60081. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60082. }
  60083. paths.push(path);
  60084. }
  60085. // lathe ribbon
  60086. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60087. return lathe;
  60088. };
  60089. /**
  60090. * Creates a plane mesh
  60091. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60092. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60093. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60094. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60095. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60096. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60097. * @param name defines the name of the mesh
  60098. * @param options defines the options used to create the mesh
  60099. * @param scene defines the hosting scene
  60100. * @returns the plane mesh
  60101. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60102. */
  60103. MeshBuilder.CreatePlane = function (name, options, scene) {
  60104. var plane = new BABYLON.Mesh(name, scene);
  60105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60106. plane._originalBuilderSideOrientation = options.sideOrientation;
  60107. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60108. vertexData.applyToMesh(plane, options.updatable);
  60109. if (options.sourcePlane) {
  60110. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60111. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60112. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60113. plane.rotate(vectorProduct, product);
  60114. }
  60115. return plane;
  60116. };
  60117. /**
  60118. * Creates a ground mesh
  60119. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60120. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60121. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60122. * @param name defines the name of the mesh
  60123. * @param options defines the options used to create the mesh
  60124. * @param scene defines the hosting scene
  60125. * @returns the ground mesh
  60126. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60127. */
  60128. MeshBuilder.CreateGround = function (name, options, scene) {
  60129. var ground = new BABYLON.GroundMesh(name, scene);
  60130. ground._setReady(false);
  60131. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60132. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60133. ground._width = options.width || 1;
  60134. ground._height = options.height || 1;
  60135. ground._maxX = ground._width / 2;
  60136. ground._maxZ = ground._height / 2;
  60137. ground._minX = -ground._maxX;
  60138. ground._minZ = -ground._maxZ;
  60139. var vertexData = BABYLON.VertexData.CreateGround(options);
  60140. vertexData.applyToMesh(ground, options.updatable);
  60141. ground._setReady(true);
  60142. return ground;
  60143. };
  60144. /**
  60145. * Creates a tiled ground mesh
  60146. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60147. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60148. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  60149. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  60150. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60151. * @param name defines the name of the mesh
  60152. * @param options defines the options used to create the mesh
  60153. * @param scene defines the hosting scene
  60154. * @returns the tiled ground mesh
  60155. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60156. */
  60157. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60158. var tiledGround = new BABYLON.Mesh(name, scene);
  60159. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60160. vertexData.applyToMesh(tiledGround, options.updatable);
  60161. return tiledGround;
  60162. };
  60163. /**
  60164. * Creates a ground mesh from a height map
  60165. * * The parameter `url` sets the URL of the height map image resource.
  60166. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60167. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60168. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60169. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60170. * * 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.
  60171. * * 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).
  60172. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60173. * @param name defines the name of the mesh
  60174. * @param url defines the url to the height map
  60175. * @param options defines the options used to create the mesh
  60176. * @param scene defines the hosting scene
  60177. * @returns the ground mesh
  60178. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60179. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60180. */
  60181. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60182. var width = options.width || 10.0;
  60183. var height = options.height || 10.0;
  60184. var subdivisions = options.subdivisions || 1 | 0;
  60185. var minHeight = options.minHeight || 0.0;
  60186. var maxHeight = options.maxHeight || 1.0;
  60187. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60188. var updatable = options.updatable;
  60189. var onReady = options.onReady;
  60190. var ground = new BABYLON.GroundMesh(name, scene);
  60191. ground._subdivisionsX = subdivisions;
  60192. ground._subdivisionsY = subdivisions;
  60193. ground._width = width;
  60194. ground._height = height;
  60195. ground._maxX = ground._width / 2.0;
  60196. ground._maxZ = ground._height / 2.0;
  60197. ground._minX = -ground._maxX;
  60198. ground._minZ = -ground._maxZ;
  60199. ground._setReady(false);
  60200. var onload = function (img) {
  60201. // Getting height map data
  60202. var canvas = document.createElement("canvas");
  60203. var context = canvas.getContext("2d");
  60204. if (!context) {
  60205. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60206. }
  60207. if (scene.isDisposed) {
  60208. return;
  60209. }
  60210. var bufferWidth = img.width;
  60211. var bufferHeight = img.height;
  60212. canvas.width = bufferWidth;
  60213. canvas.height = bufferHeight;
  60214. context.drawImage(img, 0, 0);
  60215. // Create VertexData from map data
  60216. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60217. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60218. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60219. width: width, height: height,
  60220. subdivisions: subdivisions,
  60221. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60222. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60223. });
  60224. vertexData.applyToMesh(ground, updatable);
  60225. //execute ready callback, if set
  60226. if (onReady) {
  60227. onReady(ground);
  60228. }
  60229. ground._setReady(true);
  60230. };
  60231. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60232. return ground;
  60233. };
  60234. /**
  60235. * Creates a polygon mesh
  60236. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60237. * * 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
  60238. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60239. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60240. * * 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)
  60241. * * Remember you can only change the shape positions, not their number when updating a polygon
  60242. * @param name defines the name of the mesh
  60243. * @param options defines the options used to create the mesh
  60244. * @param scene defines the hosting scene
  60245. * @returns the polygon mesh
  60246. */
  60247. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60248. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60249. var shape = options.shape;
  60250. var holes = options.holes || [];
  60251. var depth = options.depth || 0;
  60252. var contours = [];
  60253. var hole = [];
  60254. for (var i = 0; i < shape.length; i++) {
  60255. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60256. }
  60257. var epsilon = 0.00000001;
  60258. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60259. contours.pop();
  60260. }
  60261. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60262. for (var hNb = 0; hNb < holes.length; hNb++) {
  60263. hole = [];
  60264. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60265. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60266. }
  60267. polygonTriangulation.addHole(hole);
  60268. }
  60269. var polygon = polygonTriangulation.build(options.updatable, depth);
  60270. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60271. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60272. vertexData.applyToMesh(polygon, options.updatable);
  60273. return polygon;
  60274. };
  60275. ;
  60276. /**
  60277. * Creates an extruded polygon mesh, with depth in the Y direction.
  60278. * * 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)
  60279. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60280. * @param name defines the name of the mesh
  60281. * @param options defines the options used to create the mesh
  60282. * @param scene defines the hosting scene
  60283. * @returns the polygon mesh
  60284. */
  60285. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60286. return MeshBuilder.CreatePolygon(name, options, scene);
  60287. };
  60288. ;
  60289. /**
  60290. * Creates a tube mesh.
  60291. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60292. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60293. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60294. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60295. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60296. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  60297. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60298. * * 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
  60299. * * 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
  60300. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60301. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60302. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60303. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60304. * @param name defines the name of the mesh
  60305. * @param options defines the options used to create the mesh
  60306. * @param scene defines the hosting scene
  60307. * @returns the tube mesh
  60308. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60309. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60310. */
  60311. MeshBuilder.CreateTube = function (name, options, scene) {
  60312. var path = options.path;
  60313. var instance = options.instance;
  60314. var radius = 1.0;
  60315. if (instance) {
  60316. radius = instance.radius;
  60317. }
  60318. if (options.radius !== undefined) {
  60319. radius = options.radius;
  60320. }
  60321. ;
  60322. var tessellation = options.tessellation || 64 | 0;
  60323. var radiusFunction = options.radiusFunction || null;
  60324. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60325. var invertUV = options.invertUV || false;
  60326. var updatable = options.updatable;
  60327. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60328. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60329. // tube geometry
  60330. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60331. var tangents = path3D.getTangents();
  60332. var normals = path3D.getNormals();
  60333. var distances = path3D.getDistances();
  60334. var pi2 = Math.PI * 2;
  60335. var step = pi2 / tessellation * arc;
  60336. var returnRadius = function () { return radius; };
  60337. var radiusFunctionFinal = radiusFunction || returnRadius;
  60338. var circlePath;
  60339. var rad;
  60340. var normal;
  60341. var rotated;
  60342. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60343. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60344. for (var i = 0; i < path.length; i++) {
  60345. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60346. circlePath = Array(); // current circle array
  60347. normal = normals[i]; // current normal
  60348. for (var t = 0; t < tessellation; t++) {
  60349. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60350. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60351. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60352. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60353. circlePath[t] = rotated;
  60354. }
  60355. circlePaths[index] = circlePath;
  60356. index++;
  60357. }
  60358. // cap
  60359. var capPath = function (nbPoints, pathIndex) {
  60360. var pointCap = Array();
  60361. for (var i = 0; i < nbPoints; i++) {
  60362. pointCap.push(path[pathIndex]);
  60363. }
  60364. return pointCap;
  60365. };
  60366. switch (cap) {
  60367. case BABYLON.Mesh.NO_CAP:
  60368. break;
  60369. case BABYLON.Mesh.CAP_START:
  60370. circlePaths[0] = capPath(tessellation, 0);
  60371. circlePaths[1] = circlePaths[2].slice(0);
  60372. break;
  60373. case BABYLON.Mesh.CAP_END:
  60374. circlePaths[index] = circlePaths[index - 1].slice(0);
  60375. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60376. break;
  60377. case BABYLON.Mesh.CAP_ALL:
  60378. circlePaths[0] = capPath(tessellation, 0);
  60379. circlePaths[1] = circlePaths[2].slice(0);
  60380. circlePaths[index] = circlePaths[index - 1].slice(0);
  60381. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60382. break;
  60383. default:
  60384. break;
  60385. }
  60386. return circlePaths;
  60387. };
  60388. var path3D;
  60389. var pathArray;
  60390. if (instance) { // tube update
  60391. var arc = options.arc || instance.arc;
  60392. path3D = (instance.path3D).update(path);
  60393. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60394. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60395. instance.path3D = path3D;
  60396. instance.pathArray = pathArray;
  60397. instance.arc = arc;
  60398. instance.radius = radius;
  60399. return instance;
  60400. }
  60401. // tube creation
  60402. path3D = new BABYLON.Path3D(path);
  60403. var newPathArray = new Array();
  60404. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60405. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60406. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60407. tube.pathArray = pathArray;
  60408. tube.path3D = path3D;
  60409. tube.tessellation = tessellation;
  60410. tube.cap = cap;
  60411. tube.arc = options.arc;
  60412. tube.radius = radius;
  60413. return tube;
  60414. };
  60415. /**
  60416. * Creates a polyhedron mesh
  60417. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  60418. * * The parameter `size` (positive float, default 1) sets the polygon size
  60419. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60420. * * 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`
  60421. * * 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
  60422. * * 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)`)
  60423. * * 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
  60424. * * 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
  60425. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60426. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60427. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60428. * @param name defines the name of the mesh
  60429. * @param options defines the options used to create the mesh
  60430. * @param scene defines the hosting scene
  60431. * @returns the polyhedron mesh
  60432. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60433. */
  60434. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60435. var polyhedron = new BABYLON.Mesh(name, scene);
  60436. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60437. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60438. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60439. vertexData.applyToMesh(polyhedron, options.updatable);
  60440. return polyhedron;
  60441. };
  60442. /**
  60443. * Creates a decal mesh.
  60444. * 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
  60445. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60446. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60447. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60448. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60449. * @param name defines the name of the mesh
  60450. * @param sourceMesh defines the mesh where the decal must be applied
  60451. * @param options defines the options used to create the mesh
  60452. * @param scene defines the hosting scene
  60453. * @returns the decal mesh
  60454. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60455. */
  60456. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60457. var indices = sourceMesh.getIndices();
  60458. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60459. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60460. var position = options.position || BABYLON.Vector3.Zero();
  60461. var normal = options.normal || BABYLON.Vector3.Up();
  60462. var size = options.size || BABYLON.Vector3.One();
  60463. var angle = options.angle || 0;
  60464. // Getting correct rotation
  60465. if (!normal) {
  60466. var target = new BABYLON.Vector3(0, 0, 1);
  60467. var camera = sourceMesh.getScene().activeCamera;
  60468. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60469. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60470. }
  60471. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60472. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60473. var pitch = Math.atan2(normal.y, len);
  60474. // Matrix
  60475. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60476. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60477. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60478. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60479. var vertexData = new BABYLON.VertexData();
  60480. vertexData.indices = [];
  60481. vertexData.positions = [];
  60482. vertexData.normals = [];
  60483. vertexData.uvs = [];
  60484. var currentVertexDataIndex = 0;
  60485. var extractDecalVector3 = function (indexId) {
  60486. var result = new BABYLON.PositionNormalVertex();
  60487. if (!indices || !positions || !normals) {
  60488. return result;
  60489. }
  60490. var vertexId = indices[indexId];
  60491. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60492. // Send vector to decal local world
  60493. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60494. // Get normal
  60495. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60496. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60497. return result;
  60498. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60499. var clip = function (vertices, axis) {
  60500. if (vertices.length === 0) {
  60501. return vertices;
  60502. }
  60503. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60504. var clipVertices = function (v0, v1) {
  60505. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60506. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60507. };
  60508. var result = new Array();
  60509. for (var index = 0; index < vertices.length; index += 3) {
  60510. var v1Out;
  60511. var v2Out;
  60512. var v3Out;
  60513. var total = 0;
  60514. var nV1 = null;
  60515. var nV2 = null;
  60516. var nV3 = null;
  60517. var nV4 = null;
  60518. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60519. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60520. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60521. v1Out = d1 > 0;
  60522. v2Out = d2 > 0;
  60523. v3Out = d3 > 0;
  60524. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60525. switch (total) {
  60526. case 0:
  60527. result.push(vertices[index]);
  60528. result.push(vertices[index + 1]);
  60529. result.push(vertices[index + 2]);
  60530. break;
  60531. case 1:
  60532. if (v1Out) {
  60533. nV1 = vertices[index + 1];
  60534. nV2 = vertices[index + 2];
  60535. nV3 = clipVertices(vertices[index], nV1);
  60536. nV4 = clipVertices(vertices[index], nV2);
  60537. }
  60538. if (v2Out) {
  60539. nV1 = vertices[index];
  60540. nV2 = vertices[index + 2];
  60541. nV3 = clipVertices(vertices[index + 1], nV1);
  60542. nV4 = clipVertices(vertices[index + 1], nV2);
  60543. result.push(nV3);
  60544. result.push(nV2.clone());
  60545. result.push(nV1.clone());
  60546. result.push(nV2.clone());
  60547. result.push(nV3.clone());
  60548. result.push(nV4);
  60549. break;
  60550. }
  60551. if (v3Out) {
  60552. nV1 = vertices[index];
  60553. nV2 = vertices[index + 1];
  60554. nV3 = clipVertices(vertices[index + 2], nV1);
  60555. nV4 = clipVertices(vertices[index + 2], nV2);
  60556. }
  60557. if (nV1 && nV2 && nV3 && nV4) {
  60558. result.push(nV1.clone());
  60559. result.push(nV2.clone());
  60560. result.push(nV3);
  60561. result.push(nV4);
  60562. result.push(nV3.clone());
  60563. result.push(nV2.clone());
  60564. }
  60565. break;
  60566. case 2:
  60567. if (!v1Out) {
  60568. nV1 = vertices[index].clone();
  60569. nV2 = clipVertices(nV1, vertices[index + 1]);
  60570. nV3 = clipVertices(nV1, vertices[index + 2]);
  60571. result.push(nV1);
  60572. result.push(nV2);
  60573. result.push(nV3);
  60574. }
  60575. if (!v2Out) {
  60576. nV1 = vertices[index + 1].clone();
  60577. nV2 = clipVertices(nV1, vertices[index + 2]);
  60578. nV3 = clipVertices(nV1, vertices[index]);
  60579. result.push(nV1);
  60580. result.push(nV2);
  60581. result.push(nV3);
  60582. }
  60583. if (!v3Out) {
  60584. nV1 = vertices[index + 2].clone();
  60585. nV2 = clipVertices(nV1, vertices[index]);
  60586. nV3 = clipVertices(nV1, vertices[index + 1]);
  60587. result.push(nV1);
  60588. result.push(nV2);
  60589. result.push(nV3);
  60590. }
  60591. break;
  60592. case 3:
  60593. break;
  60594. }
  60595. }
  60596. return result;
  60597. };
  60598. for (var index = 0; index < indices.length; index += 3) {
  60599. var faceVertices = new Array();
  60600. faceVertices.push(extractDecalVector3(index));
  60601. faceVertices.push(extractDecalVector3(index + 1));
  60602. faceVertices.push(extractDecalVector3(index + 2));
  60603. // Clip
  60604. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60605. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60606. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60607. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60608. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60609. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60610. if (faceVertices.length === 0) {
  60611. continue;
  60612. }
  60613. // Add UVs and get back to world
  60614. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60615. var vertex = faceVertices[vIndex];
  60616. //TODO check for Int32Array | Uint32Array | Uint16Array
  60617. vertexData.indices.push(currentVertexDataIndex);
  60618. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60619. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60620. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60621. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60622. currentVertexDataIndex++;
  60623. }
  60624. }
  60625. // Return mesh
  60626. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60627. vertexData.applyToMesh(decal);
  60628. decal.position = position.clone();
  60629. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60630. return decal;
  60631. };
  60632. // Privates
  60633. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60634. // extrusion geometry
  60635. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60636. var tangents = path3D.getTangents();
  60637. var normals = path3D.getNormals();
  60638. var binormals = path3D.getBinormals();
  60639. var distances = path3D.getDistances();
  60640. var angle = 0;
  60641. var returnScale = function () { return scale !== null ? scale : 1; };
  60642. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60643. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60644. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60645. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60646. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60647. for (var i = 0; i < curve.length; i++) {
  60648. var shapePath = new Array();
  60649. var angleStep = rotate(i, distances[i]);
  60650. var scaleRatio = scl(i, distances[i]);
  60651. for (var p = 0; p < shape.length; p++) {
  60652. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60653. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60654. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60655. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60656. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60657. shapePath[p] = rotated;
  60658. }
  60659. shapePaths[index] = shapePath;
  60660. angle += angleStep;
  60661. index++;
  60662. }
  60663. // cap
  60664. var capPath = function (shapePath) {
  60665. var pointCap = Array();
  60666. var barycenter = BABYLON.Vector3.Zero();
  60667. var i;
  60668. for (i = 0; i < shapePath.length; i++) {
  60669. barycenter.addInPlace(shapePath[i]);
  60670. }
  60671. barycenter.scaleInPlace(1.0 / shapePath.length);
  60672. for (i = 0; i < shapePath.length; i++) {
  60673. pointCap.push(barycenter);
  60674. }
  60675. return pointCap;
  60676. };
  60677. switch (cap) {
  60678. case BABYLON.Mesh.NO_CAP:
  60679. break;
  60680. case BABYLON.Mesh.CAP_START:
  60681. shapePaths[0] = capPath(shapePaths[2]);
  60682. shapePaths[1] = shapePaths[2];
  60683. break;
  60684. case BABYLON.Mesh.CAP_END:
  60685. shapePaths[index] = shapePaths[index - 1];
  60686. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60687. break;
  60688. case BABYLON.Mesh.CAP_ALL:
  60689. shapePaths[0] = capPath(shapePaths[2]);
  60690. shapePaths[1] = shapePaths[2];
  60691. shapePaths[index] = shapePaths[index - 1];
  60692. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60693. break;
  60694. default:
  60695. break;
  60696. }
  60697. return shapePaths;
  60698. };
  60699. var path3D;
  60700. var pathArray;
  60701. if (instance) { // instance update
  60702. path3D = (instance.path3D).update(curve);
  60703. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60704. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60705. return instance;
  60706. }
  60707. // extruded shape creation
  60708. path3D = new BABYLON.Path3D(curve);
  60709. var newShapePaths = new Array();
  60710. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60711. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60712. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60713. extrudedGeneric.pathArray = pathArray;
  60714. extrudedGeneric.path3D = path3D;
  60715. extrudedGeneric.cap = cap;
  60716. return extrudedGeneric;
  60717. };
  60718. return MeshBuilder;
  60719. }());
  60720. BABYLON.MeshBuilder = MeshBuilder;
  60721. })(BABYLON || (BABYLON = {}));
  60722. //# sourceMappingURL=babylon.meshBuilder.js.map
  60723. var BABYLON;
  60724. (function (BABYLON) {
  60725. /**
  60726. * Draco compression (https://google.github.io/draco/)
  60727. */
  60728. var DracoCompression = /** @class */ (function () {
  60729. /**
  60730. * Constructor
  60731. */
  60732. function DracoCompression() {
  60733. }
  60734. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  60735. /**
  60736. * Returns true if the decoder is available.
  60737. */
  60738. get: function () {
  60739. return (typeof DracoDecoderModule !== "undefined" ||
  60740. (typeof WebAssembly === "object" && !!DracoCompression.Configuration.decoderWasm) ||
  60741. !!DracoCompression.Configuration.decoder);
  60742. },
  60743. enumerable: true,
  60744. configurable: true
  60745. });
  60746. /**
  60747. * Stop all async operations and release resources.
  60748. */
  60749. DracoCompression.prototype.dispose = function () {
  60750. };
  60751. /**
  60752. * Decode Draco compressed mesh data to vertex data.
  60753. * @param data The array buffer view for the Draco compression data
  60754. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60755. * @returns A promise that resolves with the decoded vertex data
  60756. */
  60757. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60758. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  60759. var module = wrappedModule.module;
  60760. var vertexData = new BABYLON.VertexData();
  60761. var buffer = new module.DecoderBuffer();
  60762. buffer.Init(data, data.byteLength);
  60763. var decoder = new module.Decoder();
  60764. var geometry;
  60765. var status;
  60766. try {
  60767. var type = decoder.GetEncodedGeometryType(buffer);
  60768. switch (type) {
  60769. case module.TRIANGULAR_MESH:
  60770. geometry = new module.Mesh();
  60771. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60772. break;
  60773. case module.POINT_CLOUD:
  60774. geometry = new module.PointCloud();
  60775. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60776. break;
  60777. default:
  60778. throw new Error("Invalid geometry type " + type);
  60779. }
  60780. if (!status.ok() || !geometry.ptr) {
  60781. throw new Error(status.error_msg());
  60782. }
  60783. var numPoints = geometry.num_points();
  60784. if (type === module.TRIANGULAR_MESH) {
  60785. var numFaces = geometry.num_faces();
  60786. var faceIndices = new module.DracoInt32Array();
  60787. try {
  60788. var indices = new Uint32Array(numFaces * 3);
  60789. for (var i = 0; i < numFaces; i++) {
  60790. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60791. var offset = i * 3;
  60792. indices[offset + 0] = faceIndices.GetValue(0);
  60793. indices[offset + 1] = faceIndices.GetValue(1);
  60794. indices[offset + 2] = faceIndices.GetValue(2);
  60795. }
  60796. vertexData.indices = indices;
  60797. }
  60798. finally {
  60799. module.destroy(faceIndices);
  60800. }
  60801. }
  60802. for (var kind in attributes) {
  60803. var uniqueId = attributes[kind];
  60804. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60805. var dracoData = new module.DracoFloat32Array();
  60806. try {
  60807. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60808. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60809. for (var i = 0; i < babylonData.length; i++) {
  60810. babylonData[i] = dracoData.GetValue(i);
  60811. }
  60812. vertexData.set(babylonData, kind);
  60813. }
  60814. finally {
  60815. module.destroy(dracoData);
  60816. }
  60817. }
  60818. }
  60819. finally {
  60820. if (geometry) {
  60821. module.destroy(geometry);
  60822. }
  60823. module.destroy(decoder);
  60824. module.destroy(buffer);
  60825. }
  60826. return vertexData;
  60827. });
  60828. };
  60829. DracoCompression._GetDecoderModule = function () {
  60830. if (!DracoCompression._DecoderModulePromise) {
  60831. var promise = void 0;
  60832. var config_1 = {};
  60833. if (typeof DracoDecoderModule !== "undefined") {
  60834. promise = Promise.resolve();
  60835. }
  60836. else if (typeof WebAssembly === "object" && DracoCompression.Configuration.decoderWasm) {
  60837. promise = Promise.all([
  60838. DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoderWasm.wrapperUrl),
  60839. DracoCompression._LoadFileAsync(DracoCompression.Configuration.decoderWasm.binaryUrl).then(function (data) {
  60840. config_1.wasmBinary = data;
  60841. })
  60842. ]);
  60843. }
  60844. else if (DracoCompression.Configuration.decoder) {
  60845. promise = DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoder.url);
  60846. }
  60847. else {
  60848. throw new Error("Invalid decoder configuration");
  60849. }
  60850. DracoCompression._DecoderModulePromise = promise.then(function () {
  60851. return new Promise(function (resolve) {
  60852. config_1.onModuleLoaded = function (decoderModule) {
  60853. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  60854. resolve({ module: decoderModule });
  60855. };
  60856. DracoDecoderModule(config_1);
  60857. });
  60858. });
  60859. }
  60860. return DracoCompression._DecoderModulePromise;
  60861. };
  60862. DracoCompression._LoadScriptAsync = function (url) {
  60863. return new Promise(function (resolve, reject) {
  60864. BABYLON.Tools.LoadScript(url, function () {
  60865. resolve();
  60866. }, function (message) {
  60867. reject(new Error(message));
  60868. });
  60869. });
  60870. };
  60871. DracoCompression._LoadFileAsync = function (url) {
  60872. return new Promise(function (resolve, reject) {
  60873. BABYLON.Tools.LoadFile(url, function (data) {
  60874. resolve(data);
  60875. }, undefined, undefined, true, function (request, exception) {
  60876. reject(exception);
  60877. });
  60878. });
  60879. };
  60880. DracoCompression._GetDefaultConfig = function () {
  60881. var configuration = {
  60882. decoder: null,
  60883. decoderWasm: null
  60884. };
  60885. if (BABYLON.Tools.IsWindowObjectExist()) {
  60886. var decoderUrl = null;
  60887. var decoderWasmBinaryUrl = null;
  60888. var decoderWasmWrapperUrl = null;
  60889. for (var i = 0; i < document.scripts.length; i++) {
  60890. var type = document.scripts[i].type;
  60891. var src = document.scripts[i].src;
  60892. switch (type) {
  60893. case "text/x-draco-decoder": {
  60894. decoderUrl = src;
  60895. break;
  60896. }
  60897. case "text/x-draco-decoder-wasm-binary": {
  60898. decoderWasmBinaryUrl = src;
  60899. break;
  60900. }
  60901. case "text/x-draco-decoder-wasm-wrapper": {
  60902. decoderWasmWrapperUrl = src;
  60903. break;
  60904. }
  60905. }
  60906. }
  60907. if (decoderUrl) {
  60908. configuration.decoder = {
  60909. url: decoderUrl
  60910. };
  60911. }
  60912. if (decoderWasmWrapperUrl && decoderWasmBinaryUrl) {
  60913. configuration.decoderWasm = {
  60914. binaryUrl: decoderWasmBinaryUrl,
  60915. wrapperUrl: decoderWasmWrapperUrl
  60916. };
  60917. }
  60918. }
  60919. return configuration;
  60920. };
  60921. /**
  60922. * Gets the configuration.
  60923. */
  60924. DracoCompression.Configuration = DracoCompression._GetDefaultConfig();
  60925. return DracoCompression;
  60926. }());
  60927. BABYLON.DracoCompression = DracoCompression;
  60928. })(BABYLON || (BABYLON = {}));
  60929. //# sourceMappingURL=babylon.dracoCompression.js.map
  60930. var BABYLON;
  60931. (function (BABYLON) {
  60932. var AudioEngine = /** @class */ (function () {
  60933. function AudioEngine() {
  60934. this._audioContext = null;
  60935. this._audioContextInitialized = false;
  60936. this.canUseWebAudio = false;
  60937. this.WarnedWebAudioUnsupported = false;
  60938. this.unlocked = false;
  60939. this.isMP3supported = false;
  60940. this.isOGGsupported = false;
  60941. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60942. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60943. this.canUseWebAudio = true;
  60944. }
  60945. var audioElem = document.createElement('audio');
  60946. try {
  60947. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60948. this.isMP3supported = true;
  60949. }
  60950. }
  60951. catch (e) {
  60952. // protect error during capability check.
  60953. }
  60954. try {
  60955. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60956. this.isOGGsupported = true;
  60957. }
  60958. }
  60959. catch (e) {
  60960. // protect error during capability check.
  60961. }
  60962. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60963. this._unlockiOSaudio();
  60964. }
  60965. else {
  60966. this.unlocked = true;
  60967. }
  60968. }
  60969. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60970. get: function () {
  60971. if (!this._audioContextInitialized) {
  60972. this._initializeAudioContext();
  60973. }
  60974. return this._audioContext;
  60975. },
  60976. enumerable: true,
  60977. configurable: true
  60978. });
  60979. AudioEngine.prototype._unlockiOSaudio = function () {
  60980. var _this = this;
  60981. var unlockaudio = function () {
  60982. if (!_this.audioContext) {
  60983. return;
  60984. }
  60985. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60986. var source = _this.audioContext.createBufferSource();
  60987. source.buffer = buffer;
  60988. source.connect(_this.audioContext.destination);
  60989. source.start(0);
  60990. setTimeout(function () {
  60991. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60992. _this.unlocked = true;
  60993. window.removeEventListener('touchend', unlockaudio, false);
  60994. if (_this.onAudioUnlocked) {
  60995. _this.onAudioUnlocked();
  60996. }
  60997. }
  60998. }, 0);
  60999. };
  61000. window.addEventListener('touchend', unlockaudio, false);
  61001. };
  61002. AudioEngine.prototype._initializeAudioContext = function () {
  61003. try {
  61004. if (this.canUseWebAudio) {
  61005. this._audioContext = new AudioContext();
  61006. // create a global volume gain node
  61007. this.masterGain = this._audioContext.createGain();
  61008. this.masterGain.gain.value = 1;
  61009. this.masterGain.connect(this._audioContext.destination);
  61010. this._audioContextInitialized = true;
  61011. }
  61012. }
  61013. catch (e) {
  61014. this.canUseWebAudio = false;
  61015. BABYLON.Tools.Error("Web Audio: " + e.message);
  61016. }
  61017. };
  61018. AudioEngine.prototype.dispose = function () {
  61019. if (this.canUseWebAudio && this._audioContextInitialized) {
  61020. if (this._connectedAnalyser && this._audioContext) {
  61021. this._connectedAnalyser.stopDebugCanvas();
  61022. this._connectedAnalyser.dispose();
  61023. this.masterGain.disconnect();
  61024. this.masterGain.connect(this._audioContext.destination);
  61025. this._connectedAnalyser = null;
  61026. }
  61027. this.masterGain.gain.value = 1;
  61028. }
  61029. this.WarnedWebAudioUnsupported = false;
  61030. };
  61031. AudioEngine.prototype.getGlobalVolume = function () {
  61032. if (this.canUseWebAudio && this._audioContextInitialized) {
  61033. return this.masterGain.gain.value;
  61034. }
  61035. else {
  61036. return -1;
  61037. }
  61038. };
  61039. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61040. if (this.canUseWebAudio && this._audioContextInitialized) {
  61041. this.masterGain.gain.value = newVolume;
  61042. }
  61043. };
  61044. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61045. if (this._connectedAnalyser) {
  61046. this._connectedAnalyser.stopDebugCanvas();
  61047. }
  61048. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61049. this._connectedAnalyser = analyser;
  61050. this.masterGain.disconnect();
  61051. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61052. }
  61053. };
  61054. return AudioEngine;
  61055. }());
  61056. BABYLON.AudioEngine = AudioEngine;
  61057. })(BABYLON || (BABYLON = {}));
  61058. //# sourceMappingURL=babylon.audioEngine.js.map
  61059. var BABYLON;
  61060. (function (BABYLON) {
  61061. var Sound = /** @class */ (function () {
  61062. /**
  61063. * Create a sound and attach it to a scene
  61064. * @param name Name of your sound
  61065. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61066. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61067. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61068. */
  61069. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61070. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61071. var _this = this;
  61072. this.autoplay = false;
  61073. this.loop = false;
  61074. this.useCustomAttenuation = false;
  61075. this.spatialSound = false;
  61076. this.refDistance = 1;
  61077. this.rolloffFactor = 1;
  61078. this.maxDistance = 100;
  61079. this.distanceModel = "linear";
  61080. this._panningModel = "equalpower";
  61081. this._playbackRate = 1;
  61082. this._streaming = false;
  61083. this._startTime = 0;
  61084. this._startOffset = 0;
  61085. this._position = BABYLON.Vector3.Zero();
  61086. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61087. this._volume = 1;
  61088. this._isReadyToPlay = false;
  61089. this.isPlaying = false;
  61090. this.isPaused = false;
  61091. this._isDirectional = false;
  61092. // Used if you'd like to create a directional sound.
  61093. // If not set, the sound will be omnidirectional
  61094. this._coneInnerAngle = 360;
  61095. this._coneOuterAngle = 360;
  61096. this._coneOuterGain = 0;
  61097. this._isOutputConnected = false;
  61098. this._urlType = "Unknown";
  61099. this.name = name;
  61100. this._scene = scene;
  61101. this._readyToPlayCallback = readyToPlayCallback;
  61102. // Default custom attenuation function is a linear attenuation
  61103. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61104. if (currentDistance < maxDistance) {
  61105. return currentVolume * (1 - currentDistance / maxDistance);
  61106. }
  61107. else {
  61108. return 0;
  61109. }
  61110. };
  61111. if (options) {
  61112. this.autoplay = options.autoplay || false;
  61113. this.loop = options.loop || false;
  61114. // if volume === 0, we need another way to check this option
  61115. if (options.volume !== undefined) {
  61116. this._volume = options.volume;
  61117. }
  61118. this.spatialSound = options.spatialSound || false;
  61119. this.maxDistance = options.maxDistance || 100;
  61120. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61121. this.rolloffFactor = options.rolloffFactor || 1;
  61122. this.refDistance = options.refDistance || 1;
  61123. this.distanceModel = options.distanceModel || "linear";
  61124. this._playbackRate = options.playbackRate || 1;
  61125. this._streaming = options.streaming || false;
  61126. }
  61127. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61128. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61129. this._soundGain.gain.value = this._volume;
  61130. this._inputAudioNode = this._soundGain;
  61131. this._ouputAudioNode = this._soundGain;
  61132. if (this.spatialSound) {
  61133. this._createSpatialParameters();
  61134. }
  61135. this._scene.mainSoundTrack.AddSound(this);
  61136. var validParameter = true;
  61137. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61138. if (urlOrArrayBuffer) {
  61139. try {
  61140. if (typeof (urlOrArrayBuffer) === "string")
  61141. this._urlType = "String";
  61142. if (Array.isArray(urlOrArrayBuffer))
  61143. this._urlType = "Array";
  61144. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61145. this._urlType = "ArrayBuffer";
  61146. var urls = [];
  61147. var codecSupportedFound = false;
  61148. switch (this._urlType) {
  61149. case "ArrayBuffer":
  61150. if (urlOrArrayBuffer.byteLength > 0) {
  61151. codecSupportedFound = true;
  61152. this._soundLoaded(urlOrArrayBuffer);
  61153. }
  61154. break;
  61155. case "String":
  61156. urls.push(urlOrArrayBuffer);
  61157. case "Array":
  61158. if (urls.length === 0)
  61159. urls = urlOrArrayBuffer;
  61160. // If we found a supported format, we load it immediately and stop the loop
  61161. for (var i = 0; i < urls.length; i++) {
  61162. var url = urls[i];
  61163. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61164. codecSupportedFound = true;
  61165. }
  61166. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61167. codecSupportedFound = true;
  61168. }
  61169. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61170. codecSupportedFound = true;
  61171. }
  61172. if (url.indexOf("blob:") !== -1) {
  61173. codecSupportedFound = true;
  61174. }
  61175. if (codecSupportedFound) {
  61176. // Loading sound using XHR2
  61177. if (!this._streaming) {
  61178. this._scene._loadFile(url, function (data) {
  61179. _this._soundLoaded(data);
  61180. }, undefined, true, true, function (exception) {
  61181. if (exception) {
  61182. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61183. }
  61184. BABYLON.Tools.Error("Sound creation aborted.");
  61185. _this._scene.mainSoundTrack.RemoveSound(_this);
  61186. });
  61187. }
  61188. // Streaming sound using HTML5 Audio tag
  61189. else {
  61190. this._htmlAudioElement = new Audio(url);
  61191. this._htmlAudioElement.controls = false;
  61192. this._htmlAudioElement.loop = this.loop;
  61193. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61194. this._htmlAudioElement.preload = "auto";
  61195. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61196. _this._isReadyToPlay = true;
  61197. if (_this.autoplay) {
  61198. _this.play();
  61199. }
  61200. if (_this._readyToPlayCallback) {
  61201. _this._readyToPlayCallback();
  61202. }
  61203. });
  61204. document.body.appendChild(this._htmlAudioElement);
  61205. }
  61206. break;
  61207. }
  61208. }
  61209. break;
  61210. default:
  61211. validParameter = false;
  61212. break;
  61213. }
  61214. if (!validParameter) {
  61215. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61216. }
  61217. else {
  61218. if (!codecSupportedFound) {
  61219. this._isReadyToPlay = true;
  61220. // Simulating a ready to play event to avoid breaking code path
  61221. if (this._readyToPlayCallback) {
  61222. window.setTimeout(function () {
  61223. if (_this._readyToPlayCallback) {
  61224. _this._readyToPlayCallback();
  61225. }
  61226. }, 1000);
  61227. }
  61228. }
  61229. }
  61230. }
  61231. catch (ex) {
  61232. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61233. this._scene.mainSoundTrack.RemoveSound(this);
  61234. }
  61235. }
  61236. }
  61237. else {
  61238. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61239. this._scene.mainSoundTrack.AddSound(this);
  61240. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61241. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61242. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61243. }
  61244. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61245. if (this._readyToPlayCallback) {
  61246. window.setTimeout(function () {
  61247. if (_this._readyToPlayCallback) {
  61248. _this._readyToPlayCallback();
  61249. }
  61250. }, 1000);
  61251. }
  61252. }
  61253. }
  61254. Sound.prototype.dispose = function () {
  61255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61256. if (this.isPlaying) {
  61257. this.stop();
  61258. }
  61259. this._isReadyToPlay = false;
  61260. if (this.soundTrackId === -1) {
  61261. this._scene.mainSoundTrack.RemoveSound(this);
  61262. }
  61263. else {
  61264. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61265. }
  61266. if (this._soundGain) {
  61267. this._soundGain.disconnect();
  61268. this._soundGain = null;
  61269. }
  61270. if (this._soundPanner) {
  61271. this._soundPanner.disconnect();
  61272. this._soundPanner = null;
  61273. }
  61274. if (this._soundSource) {
  61275. this._soundSource.disconnect();
  61276. this._soundSource = null;
  61277. }
  61278. this._audioBuffer = null;
  61279. if (this._htmlAudioElement) {
  61280. this._htmlAudioElement.pause();
  61281. this._htmlAudioElement.src = "";
  61282. document.body.removeChild(this._htmlAudioElement);
  61283. }
  61284. if (this._connectedMesh && this._registerFunc) {
  61285. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61286. this._connectedMesh = null;
  61287. }
  61288. }
  61289. };
  61290. Sound.prototype.isReady = function () {
  61291. return this._isReadyToPlay;
  61292. };
  61293. Sound.prototype._soundLoaded = function (audioData) {
  61294. var _this = this;
  61295. if (!BABYLON.Engine.audioEngine.audioContext) {
  61296. return;
  61297. }
  61298. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61299. _this._audioBuffer = buffer;
  61300. _this._isReadyToPlay = true;
  61301. if (_this.autoplay) {
  61302. _this.play();
  61303. }
  61304. if (_this._readyToPlayCallback) {
  61305. _this._readyToPlayCallback();
  61306. }
  61307. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61308. };
  61309. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61310. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61311. this._audioBuffer = audioBuffer;
  61312. this._isReadyToPlay = true;
  61313. }
  61314. };
  61315. Sound.prototype.updateOptions = function (options) {
  61316. if (options) {
  61317. this.loop = options.loop || this.loop;
  61318. this.maxDistance = options.maxDistance || this.maxDistance;
  61319. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61320. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61321. this.refDistance = options.refDistance || this.refDistance;
  61322. this.distanceModel = options.distanceModel || this.distanceModel;
  61323. this._playbackRate = options.playbackRate || this._playbackRate;
  61324. this._updateSpatialParameters();
  61325. if (this.isPlaying) {
  61326. if (this._streaming) {
  61327. this._htmlAudioElement.playbackRate = this._playbackRate;
  61328. }
  61329. else {
  61330. if (this._soundSource) {
  61331. this._soundSource.playbackRate.value = this._playbackRate;
  61332. }
  61333. }
  61334. }
  61335. }
  61336. };
  61337. Sound.prototype._createSpatialParameters = function () {
  61338. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61339. if (this._scene.headphone) {
  61340. this._panningModel = "HRTF";
  61341. }
  61342. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61343. this._updateSpatialParameters();
  61344. this._soundPanner.connect(this._ouputAudioNode);
  61345. this._inputAudioNode = this._soundPanner;
  61346. }
  61347. };
  61348. Sound.prototype._updateSpatialParameters = function () {
  61349. if (this.spatialSound && this._soundPanner) {
  61350. if (this.useCustomAttenuation) {
  61351. // Tricks to disable in a way embedded Web Audio attenuation
  61352. this._soundPanner.distanceModel = "linear";
  61353. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61354. this._soundPanner.refDistance = 1;
  61355. this._soundPanner.rolloffFactor = 1;
  61356. this._soundPanner.panningModel = this._panningModel;
  61357. }
  61358. else {
  61359. this._soundPanner.distanceModel = this.distanceModel;
  61360. this._soundPanner.maxDistance = this.maxDistance;
  61361. this._soundPanner.refDistance = this.refDistance;
  61362. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61363. this._soundPanner.panningModel = this._panningModel;
  61364. }
  61365. }
  61366. };
  61367. Sound.prototype.switchPanningModelToHRTF = function () {
  61368. this._panningModel = "HRTF";
  61369. this._switchPanningModel();
  61370. };
  61371. Sound.prototype.switchPanningModelToEqualPower = function () {
  61372. this._panningModel = "equalpower";
  61373. this._switchPanningModel();
  61374. };
  61375. Sound.prototype._switchPanningModel = function () {
  61376. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61377. this._soundPanner.panningModel = this._panningModel;
  61378. }
  61379. };
  61380. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61381. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61382. if (this._isOutputConnected) {
  61383. this._ouputAudioNode.disconnect();
  61384. }
  61385. this._ouputAudioNode.connect(soundTrackAudioNode);
  61386. this._isOutputConnected = true;
  61387. }
  61388. };
  61389. /**
  61390. * Transform this sound into a directional source
  61391. * @param coneInnerAngle Size of the inner cone in degree
  61392. * @param coneOuterAngle Size of the outer cone in degree
  61393. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61394. */
  61395. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61396. if (coneOuterAngle < coneInnerAngle) {
  61397. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61398. return;
  61399. }
  61400. this._coneInnerAngle = coneInnerAngle;
  61401. this._coneOuterAngle = coneOuterAngle;
  61402. this._coneOuterGain = coneOuterGain;
  61403. this._isDirectional = true;
  61404. if (this.isPlaying && this.loop) {
  61405. this.stop();
  61406. this.play();
  61407. }
  61408. };
  61409. Sound.prototype.setPosition = function (newPosition) {
  61410. this._position = newPosition;
  61411. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61412. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61413. }
  61414. };
  61415. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61416. this._localDirection = newLocalDirection;
  61417. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61418. this._updateDirection();
  61419. }
  61420. };
  61421. Sound.prototype._updateDirection = function () {
  61422. if (!this._connectedMesh || !this._soundPanner) {
  61423. return;
  61424. }
  61425. var mat = this._connectedMesh.getWorldMatrix();
  61426. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61427. direction.normalize();
  61428. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61429. };
  61430. Sound.prototype.updateDistanceFromListener = function () {
  61431. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61432. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61433. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61434. }
  61435. };
  61436. Sound.prototype.setAttenuationFunction = function (callback) {
  61437. this._customAttenuationFunction = callback;
  61438. };
  61439. /**
  61440. * Play the sound
  61441. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61442. * @param offset (optional) Start the sound setting it at a specific time
  61443. */
  61444. Sound.prototype.play = function (time, offset) {
  61445. var _this = this;
  61446. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61447. try {
  61448. if (this._startOffset < 0) {
  61449. time = -this._startOffset;
  61450. this._startOffset = 0;
  61451. }
  61452. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61453. if (!this._soundSource || !this._streamingSource) {
  61454. if (this.spatialSound && this._soundPanner) {
  61455. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61456. if (this._isDirectional) {
  61457. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61458. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61459. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61460. if (this._connectedMesh) {
  61461. this._updateDirection();
  61462. }
  61463. else {
  61464. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61465. }
  61466. }
  61467. }
  61468. }
  61469. if (this._streaming) {
  61470. if (!this._streamingSource) {
  61471. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61472. this._htmlAudioElement.onended = function () { _this._onended(); };
  61473. this._htmlAudioElement.playbackRate = this._playbackRate;
  61474. }
  61475. this._streamingSource.disconnect();
  61476. this._streamingSource.connect(this._inputAudioNode);
  61477. this._htmlAudioElement.play();
  61478. }
  61479. else {
  61480. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61481. this._soundSource.buffer = this._audioBuffer;
  61482. this._soundSource.connect(this._inputAudioNode);
  61483. this._soundSource.loop = this.loop;
  61484. this._soundSource.playbackRate.value = this._playbackRate;
  61485. this._soundSource.onended = function () { _this._onended(); };
  61486. if (this._soundSource.buffer) {
  61487. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61488. }
  61489. }
  61490. this._startTime = startTime;
  61491. this.isPlaying = true;
  61492. this.isPaused = false;
  61493. }
  61494. catch (ex) {
  61495. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61496. }
  61497. }
  61498. };
  61499. Sound.prototype._onended = function () {
  61500. this.isPlaying = false;
  61501. if (this.onended) {
  61502. this.onended();
  61503. }
  61504. };
  61505. /**
  61506. * Stop the sound
  61507. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61508. */
  61509. Sound.prototype.stop = function (time) {
  61510. if (this.isPlaying) {
  61511. if (this._streaming) {
  61512. this._htmlAudioElement.pause();
  61513. // Test needed for Firefox or it will generate an Invalid State Error
  61514. if (this._htmlAudioElement.currentTime > 0) {
  61515. this._htmlAudioElement.currentTime = 0;
  61516. }
  61517. }
  61518. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61519. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61520. this._soundSource.stop(stopTime);
  61521. this._soundSource.onended = function () { };
  61522. if (!this.isPaused) {
  61523. this._startOffset = 0;
  61524. }
  61525. }
  61526. this.isPlaying = false;
  61527. }
  61528. };
  61529. Sound.prototype.pause = function () {
  61530. if (this.isPlaying) {
  61531. this.isPaused = true;
  61532. if (this._streaming) {
  61533. this._htmlAudioElement.pause();
  61534. }
  61535. else if (BABYLON.Engine.audioEngine.audioContext) {
  61536. this.stop(0);
  61537. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61538. }
  61539. }
  61540. };
  61541. Sound.prototype.setVolume = function (newVolume, time) {
  61542. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61543. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61544. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61545. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61546. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61547. }
  61548. else {
  61549. this._soundGain.gain.value = newVolume;
  61550. }
  61551. }
  61552. this._volume = newVolume;
  61553. };
  61554. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61555. this._playbackRate = newPlaybackRate;
  61556. if (this.isPlaying) {
  61557. if (this._streaming) {
  61558. this._htmlAudioElement.playbackRate = this._playbackRate;
  61559. }
  61560. else if (this._soundSource) {
  61561. this._soundSource.playbackRate.value = this._playbackRate;
  61562. }
  61563. }
  61564. };
  61565. Sound.prototype.getVolume = function () {
  61566. return this._volume;
  61567. };
  61568. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61569. var _this = this;
  61570. if (this._connectedMesh && this._registerFunc) {
  61571. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61572. this._registerFunc = null;
  61573. }
  61574. this._connectedMesh = meshToConnectTo;
  61575. if (!this.spatialSound) {
  61576. this.spatialSound = true;
  61577. this._createSpatialParameters();
  61578. if (this.isPlaying && this.loop) {
  61579. this.stop();
  61580. this.play();
  61581. }
  61582. }
  61583. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61584. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61585. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61586. };
  61587. Sound.prototype.detachFromMesh = function () {
  61588. if (this._connectedMesh && this._registerFunc) {
  61589. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61590. this._registerFunc = null;
  61591. this._connectedMesh = null;
  61592. }
  61593. };
  61594. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61595. if (!node.getBoundingInfo) {
  61596. return;
  61597. }
  61598. var mesh = node;
  61599. var boundingInfo = mesh.getBoundingInfo();
  61600. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61601. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61602. this._updateDirection();
  61603. }
  61604. };
  61605. Sound.prototype.clone = function () {
  61606. var _this = this;
  61607. if (!this._streaming) {
  61608. var setBufferAndRun = function () {
  61609. if (_this._isReadyToPlay) {
  61610. clonedSound._audioBuffer = _this.getAudioBuffer();
  61611. clonedSound._isReadyToPlay = true;
  61612. if (clonedSound.autoplay) {
  61613. clonedSound.play();
  61614. }
  61615. }
  61616. else {
  61617. window.setTimeout(setBufferAndRun, 300);
  61618. }
  61619. };
  61620. var currentOptions = {
  61621. autoplay: this.autoplay, loop: this.loop,
  61622. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61623. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61624. refDistance: this.refDistance, distanceModel: this.distanceModel
  61625. };
  61626. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61627. if (this.useCustomAttenuation) {
  61628. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61629. }
  61630. clonedSound.setPosition(this._position);
  61631. clonedSound.setPlaybackRate(this._playbackRate);
  61632. setBufferAndRun();
  61633. return clonedSound;
  61634. }
  61635. // Can't clone a streaming sound
  61636. else {
  61637. return null;
  61638. }
  61639. };
  61640. Sound.prototype.getAudioBuffer = function () {
  61641. return this._audioBuffer;
  61642. };
  61643. Sound.prototype.serialize = function () {
  61644. var serializationObject = {
  61645. name: this.name,
  61646. url: this.name,
  61647. autoplay: this.autoplay,
  61648. loop: this.loop,
  61649. volume: this._volume,
  61650. spatialSound: this.spatialSound,
  61651. maxDistance: this.maxDistance,
  61652. rolloffFactor: this.rolloffFactor,
  61653. refDistance: this.refDistance,
  61654. distanceModel: this.distanceModel,
  61655. playbackRate: this._playbackRate,
  61656. panningModel: this._panningModel,
  61657. soundTrackId: this.soundTrackId
  61658. };
  61659. if (this.spatialSound) {
  61660. if (this._connectedMesh)
  61661. serializationObject.connectedMeshId = this._connectedMesh.id;
  61662. serializationObject.position = this._position.asArray();
  61663. serializationObject.refDistance = this.refDistance;
  61664. serializationObject.distanceModel = this.distanceModel;
  61665. serializationObject.isDirectional = this._isDirectional;
  61666. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61667. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61668. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61669. serializationObject.coneOuterGain = this._coneOuterGain;
  61670. }
  61671. return serializationObject;
  61672. };
  61673. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61674. var soundName = parsedSound.name;
  61675. var soundUrl;
  61676. if (parsedSound.url) {
  61677. soundUrl = rootUrl + parsedSound.url;
  61678. }
  61679. else {
  61680. soundUrl = rootUrl + soundName;
  61681. }
  61682. var options = {
  61683. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61684. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61685. rolloffFactor: parsedSound.rolloffFactor,
  61686. refDistance: parsedSound.refDistance,
  61687. distanceModel: parsedSound.distanceModel,
  61688. playbackRate: parsedSound.playbackRate
  61689. };
  61690. var newSound;
  61691. if (!sourceSound) {
  61692. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61693. scene._addPendingData(newSound);
  61694. }
  61695. else {
  61696. var setBufferAndRun = function () {
  61697. if (sourceSound._isReadyToPlay) {
  61698. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61699. newSound._isReadyToPlay = true;
  61700. if (newSound.autoplay) {
  61701. newSound.play();
  61702. }
  61703. }
  61704. else {
  61705. window.setTimeout(setBufferAndRun, 300);
  61706. }
  61707. };
  61708. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61709. setBufferAndRun();
  61710. }
  61711. if (parsedSound.position) {
  61712. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61713. newSound.setPosition(soundPosition);
  61714. }
  61715. if (parsedSound.isDirectional) {
  61716. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61717. if (parsedSound.localDirectionToMesh) {
  61718. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61719. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61720. }
  61721. }
  61722. if (parsedSound.connectedMeshId) {
  61723. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61724. if (connectedMesh) {
  61725. newSound.attachToMesh(connectedMesh);
  61726. }
  61727. }
  61728. return newSound;
  61729. };
  61730. return Sound;
  61731. }());
  61732. BABYLON.Sound = Sound;
  61733. })(BABYLON || (BABYLON = {}));
  61734. //# sourceMappingURL=babylon.sound.js.map
  61735. var BABYLON;
  61736. (function (BABYLON) {
  61737. var SoundTrack = /** @class */ (function () {
  61738. function SoundTrack(scene, options) {
  61739. this.id = -1;
  61740. this._isMainTrack = false;
  61741. this._isInitialized = false;
  61742. this._scene = scene;
  61743. this.soundCollection = new Array();
  61744. this._options = options;
  61745. if (!this._isMainTrack) {
  61746. this._scene.soundTracks.push(this);
  61747. this.id = this._scene.soundTracks.length - 1;
  61748. }
  61749. }
  61750. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61751. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61752. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61753. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61754. if (this._options) {
  61755. if (this._options.volume) {
  61756. this._outputAudioNode.gain.value = this._options.volume;
  61757. }
  61758. if (this._options.mainTrack) {
  61759. this._isMainTrack = this._options.mainTrack;
  61760. }
  61761. }
  61762. this._isInitialized = true;
  61763. }
  61764. };
  61765. SoundTrack.prototype.dispose = function () {
  61766. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61767. if (this._connectedAnalyser) {
  61768. this._connectedAnalyser.stopDebugCanvas();
  61769. }
  61770. while (this.soundCollection.length) {
  61771. this.soundCollection[0].dispose();
  61772. }
  61773. if (this._outputAudioNode) {
  61774. this._outputAudioNode.disconnect();
  61775. }
  61776. this._outputAudioNode = null;
  61777. }
  61778. };
  61779. SoundTrack.prototype.AddSound = function (sound) {
  61780. if (!this._isInitialized) {
  61781. this._initializeSoundTrackAudioGraph();
  61782. }
  61783. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61784. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61785. }
  61786. if (sound.soundTrackId) {
  61787. if (sound.soundTrackId === -1) {
  61788. this._scene.mainSoundTrack.RemoveSound(sound);
  61789. }
  61790. else {
  61791. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61792. }
  61793. }
  61794. this.soundCollection.push(sound);
  61795. sound.soundTrackId = this.id;
  61796. };
  61797. SoundTrack.prototype.RemoveSound = function (sound) {
  61798. var index = this.soundCollection.indexOf(sound);
  61799. if (index !== -1) {
  61800. this.soundCollection.splice(index, 1);
  61801. }
  61802. };
  61803. SoundTrack.prototype.setVolume = function (newVolume) {
  61804. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61805. this._outputAudioNode.gain.value = newVolume;
  61806. }
  61807. };
  61808. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61810. for (var i = 0; i < this.soundCollection.length; i++) {
  61811. this.soundCollection[i].switchPanningModelToHRTF();
  61812. }
  61813. }
  61814. };
  61815. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61816. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61817. for (var i = 0; i < this.soundCollection.length; i++) {
  61818. this.soundCollection[i].switchPanningModelToEqualPower();
  61819. }
  61820. }
  61821. };
  61822. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61823. if (this._connectedAnalyser) {
  61824. this._connectedAnalyser.stopDebugCanvas();
  61825. }
  61826. this._connectedAnalyser = analyser;
  61827. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61828. this._outputAudioNode.disconnect();
  61829. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61830. }
  61831. };
  61832. return SoundTrack;
  61833. }());
  61834. BABYLON.SoundTrack = SoundTrack;
  61835. })(BABYLON || (BABYLON = {}));
  61836. //# sourceMappingURL=babylon.soundtrack.js.map
  61837. var BABYLON;
  61838. (function (BABYLON) {
  61839. var Analyser = /** @class */ (function () {
  61840. function Analyser(scene) {
  61841. this.SMOOTHING = 0.75;
  61842. this.FFT_SIZE = 512;
  61843. this.BARGRAPHAMPLITUDE = 256;
  61844. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61845. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61846. this._scene = scene;
  61847. this._audioEngine = BABYLON.Engine.audioEngine;
  61848. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61849. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61850. this._webAudioAnalyser.minDecibels = -140;
  61851. this._webAudioAnalyser.maxDecibels = 0;
  61852. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61853. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61854. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61855. }
  61856. }
  61857. Analyser.prototype.getFrequencyBinCount = function () {
  61858. if (this._audioEngine.canUseWebAudio) {
  61859. return this._webAudioAnalyser.frequencyBinCount;
  61860. }
  61861. else {
  61862. return 0;
  61863. }
  61864. };
  61865. Analyser.prototype.getByteFrequencyData = function () {
  61866. if (this._audioEngine.canUseWebAudio) {
  61867. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61868. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61869. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61870. }
  61871. return this._byteFreqs;
  61872. };
  61873. Analyser.prototype.getByteTimeDomainData = function () {
  61874. if (this._audioEngine.canUseWebAudio) {
  61875. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61876. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61877. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61878. }
  61879. return this._byteTime;
  61880. };
  61881. Analyser.prototype.getFloatFrequencyData = function () {
  61882. if (this._audioEngine.canUseWebAudio) {
  61883. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61884. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61885. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61886. }
  61887. return this._floatFreqs;
  61888. };
  61889. Analyser.prototype.drawDebugCanvas = function () {
  61890. var _this = this;
  61891. if (this._audioEngine.canUseWebAudio) {
  61892. if (!this._debugCanvas) {
  61893. this._debugCanvas = document.createElement("canvas");
  61894. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61895. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61896. this._debugCanvas.style.position = "absolute";
  61897. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61898. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61899. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61900. document.body.appendChild(this._debugCanvas);
  61901. this._registerFunc = function () {
  61902. _this.drawDebugCanvas();
  61903. };
  61904. this._scene.registerBeforeRender(this._registerFunc);
  61905. }
  61906. if (this._registerFunc && this._debugCanvasContext) {
  61907. var workingArray = this.getByteFrequencyData();
  61908. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61909. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61910. // Draw the frequency domain chart.
  61911. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61912. var value = workingArray[i];
  61913. var percent = value / this.BARGRAPHAMPLITUDE;
  61914. var height = this.DEBUGCANVASSIZE.height * percent;
  61915. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61916. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61917. var hue = i / this.getFrequencyBinCount() * 360;
  61918. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61919. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61920. }
  61921. }
  61922. }
  61923. };
  61924. Analyser.prototype.stopDebugCanvas = function () {
  61925. if (this._debugCanvas) {
  61926. if (this._registerFunc) {
  61927. this._scene.unregisterBeforeRender(this._registerFunc);
  61928. this._registerFunc = null;
  61929. }
  61930. document.body.removeChild(this._debugCanvas);
  61931. this._debugCanvas = null;
  61932. this._debugCanvasContext = null;
  61933. }
  61934. };
  61935. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61936. if (this._audioEngine.canUseWebAudio) {
  61937. inputAudioNode.connect(this._webAudioAnalyser);
  61938. this._webAudioAnalyser.connect(outputAudioNode);
  61939. }
  61940. };
  61941. Analyser.prototype.dispose = function () {
  61942. if (this._audioEngine.canUseWebAudio) {
  61943. this._webAudioAnalyser.disconnect();
  61944. }
  61945. };
  61946. return Analyser;
  61947. }());
  61948. BABYLON.Analyser = Analyser;
  61949. })(BABYLON || (BABYLON = {}));
  61950. //# sourceMappingURL=babylon.analyser.js.map
  61951. var BABYLON;
  61952. (function (BABYLON) {
  61953. var CubeTexture = /** @class */ (function (_super) {
  61954. __extends(CubeTexture, _super);
  61955. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61956. if (extensions === void 0) { extensions = null; }
  61957. if (noMipmap === void 0) { noMipmap = false; }
  61958. if (files === void 0) { files = null; }
  61959. if (onLoad === void 0) { onLoad = null; }
  61960. if (onError === void 0) { onError = null; }
  61961. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61962. if (prefiltered === void 0) { prefiltered = false; }
  61963. if (forcedExtension === void 0) { forcedExtension = null; }
  61964. var _this = _super.call(this, scene) || this;
  61965. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61966. /**
  61967. * Gets or sets the center of the bounding box associated with the cube texture
  61968. * It must define where the camera used to render the texture was set
  61969. */
  61970. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61971. _this._rotationY = 0;
  61972. _this.name = rootUrl;
  61973. _this.url = rootUrl;
  61974. _this._noMipmap = noMipmap;
  61975. _this.hasAlpha = false;
  61976. _this._format = format;
  61977. _this._prefiltered = prefiltered;
  61978. _this.isCube = true;
  61979. _this._textureMatrix = BABYLON.Matrix.Identity();
  61980. if (prefiltered) {
  61981. _this.gammaSpace = false;
  61982. }
  61983. if (!rootUrl && !files) {
  61984. return _this;
  61985. }
  61986. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61987. var lastDot = rootUrl.lastIndexOf(".");
  61988. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61989. var isDDS = (extension === ".dds");
  61990. if (!files) {
  61991. if (!isDDS && !extensions) {
  61992. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61993. }
  61994. files = [];
  61995. if (extensions) {
  61996. for (var index = 0; index < extensions.length; index++) {
  61997. files.push(rootUrl + extensions[index]);
  61998. }
  61999. }
  62000. }
  62001. _this._files = files;
  62002. if (!_this._texture) {
  62003. if (!scene.useDelayedTextureLoading) {
  62004. if (prefiltered) {
  62005. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62006. }
  62007. else {
  62008. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62009. }
  62010. }
  62011. else {
  62012. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62013. }
  62014. }
  62015. else if (onLoad) {
  62016. if (_this._texture.isReady) {
  62017. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62018. }
  62019. else {
  62020. _this._texture.onLoadedObservable.add(onLoad);
  62021. }
  62022. }
  62023. return _this;
  62024. }
  62025. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62026. get: function () {
  62027. return this._boundingBoxSize;
  62028. },
  62029. /**
  62030. * Gets or sets the size of the bounding box associated with the cube texture
  62031. * When defined, the cubemap will switch to local mode
  62032. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62033. * @example https://www.babylonjs-playground.com/#RNASML
  62034. */
  62035. set: function (value) {
  62036. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62037. return;
  62038. }
  62039. this._boundingBoxSize = value;
  62040. var scene = this.getScene();
  62041. if (scene) {
  62042. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62043. }
  62044. },
  62045. enumerable: true,
  62046. configurable: true
  62047. });
  62048. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62049. /**
  62050. * Gets texture matrix rotation angle around Y axis radians.
  62051. */
  62052. get: function () {
  62053. return this._rotationY;
  62054. },
  62055. /**
  62056. * Sets texture matrix rotation angle around Y axis in radians.
  62057. */
  62058. set: function (value) {
  62059. this._rotationY = value;
  62060. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62061. },
  62062. enumerable: true,
  62063. configurable: true
  62064. });
  62065. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62066. var rootUrlKey = "";
  62067. files.forEach(function (url) { return rootUrlKey += url; });
  62068. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62069. };
  62070. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62071. if (forcedExtension === void 0) { forcedExtension = null; }
  62072. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62073. };
  62074. // Methods
  62075. CubeTexture.prototype.delayLoad = function () {
  62076. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62077. return;
  62078. }
  62079. var scene = this.getScene();
  62080. if (!scene) {
  62081. return;
  62082. }
  62083. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62084. this._texture = this._getFromCache(this.url, this._noMipmap);
  62085. if (!this._texture) {
  62086. if (this._prefiltered) {
  62087. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62088. }
  62089. else {
  62090. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62091. }
  62092. }
  62093. };
  62094. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62095. return this._textureMatrix;
  62096. };
  62097. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62098. this._textureMatrix = value;
  62099. };
  62100. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62101. var texture = BABYLON.SerializationHelper.Parse(function () {
  62102. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62103. }, parsedTexture, scene);
  62104. // Local Cubemaps
  62105. if (parsedTexture.boundingBoxPosition) {
  62106. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62107. }
  62108. if (parsedTexture.boundingBoxSize) {
  62109. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62110. }
  62111. // Animations
  62112. if (parsedTexture.animations) {
  62113. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62114. var parsedAnimation = parsedTexture.animations[animationIndex];
  62115. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62116. }
  62117. }
  62118. return texture;
  62119. };
  62120. CubeTexture.prototype.clone = function () {
  62121. var _this = this;
  62122. return BABYLON.SerializationHelper.Clone(function () {
  62123. var scene = _this.getScene();
  62124. if (!scene) {
  62125. return _this;
  62126. }
  62127. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62128. }, this);
  62129. };
  62130. __decorate([
  62131. BABYLON.serialize("rotationY")
  62132. ], CubeTexture.prototype, "_rotationY", void 0);
  62133. return CubeTexture;
  62134. }(BABYLON.BaseTexture));
  62135. BABYLON.CubeTexture = CubeTexture;
  62136. })(BABYLON || (BABYLON = {}));
  62137. //# sourceMappingURL=babylon.cubeTexture.js.map
  62138. var BABYLON;
  62139. (function (BABYLON) {
  62140. var RenderTargetTexture = /** @class */ (function (_super) {
  62141. __extends(RenderTargetTexture, _super);
  62142. /**
  62143. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62144. * or used a shadow, depth texture...
  62145. * @param name The friendly name of the texture
  62146. * @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)
  62147. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62148. * @param generateMipMaps True if mip maps need to be generated after render.
  62149. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62150. * @param type The type of the buffer in the RTT (int, half float, float...)
  62151. * @param isCube True if a cube texture needs to be created
  62152. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62153. * @param generateDepthBuffer True to generate a depth buffer
  62154. * @param generateStencilBuffer True to generate a stencil buffer
  62155. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62156. */
  62157. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62158. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62159. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62160. if (isCube === void 0) { isCube = false; }
  62161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62162. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62163. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62164. if (isMulti === void 0) { isMulti = false; }
  62165. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62166. _this.isCube = isCube;
  62167. /**
  62168. * Use this list to define the list of mesh you want to render.
  62169. */
  62170. _this.renderList = new Array();
  62171. _this.renderParticles = true;
  62172. _this.renderSprites = false;
  62173. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62174. _this.ignoreCameraViewport = false;
  62175. // Events
  62176. /**
  62177. * An event triggered when the texture is unbind.
  62178. */
  62179. _this.onBeforeBindObservable = new BABYLON.Observable();
  62180. /**
  62181. * An event triggered when the texture is unbind.
  62182. */
  62183. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62184. /**
  62185. * An event triggered before rendering the texture
  62186. */
  62187. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62188. /**
  62189. * An event triggered after rendering the texture
  62190. */
  62191. _this.onAfterRenderObservable = new BABYLON.Observable();
  62192. /**
  62193. * An event triggered after the texture clear
  62194. */
  62195. _this.onClearObservable = new BABYLON.Observable();
  62196. _this._currentRefreshId = -1;
  62197. _this._refreshRate = 1;
  62198. _this._samples = 1;
  62199. /**
  62200. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62201. * It must define where the camera used to render the texture is set
  62202. */
  62203. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62204. scene = _this.getScene();
  62205. if (!scene) {
  62206. return _this;
  62207. }
  62208. _this._engine = scene.getEngine();
  62209. _this.name = name;
  62210. _this.isRenderTarget = true;
  62211. _this._initialSizeParameter = size;
  62212. _this._processSizeParameter(size);
  62213. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62214. });
  62215. _this._generateMipMaps = generateMipMaps ? true : false;
  62216. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62217. // Rendering groups
  62218. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62219. if (isMulti) {
  62220. return _this;
  62221. }
  62222. _this._renderTargetOptions = {
  62223. generateMipMaps: generateMipMaps,
  62224. type: type,
  62225. samplingMode: samplingMode,
  62226. generateDepthBuffer: generateDepthBuffer,
  62227. generateStencilBuffer: generateStencilBuffer
  62228. };
  62229. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62230. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62231. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62232. }
  62233. if (isCube) {
  62234. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62235. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62236. _this._textureMatrix = BABYLON.Matrix.Identity();
  62237. }
  62238. else {
  62239. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62240. }
  62241. return _this;
  62242. }
  62243. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62244. get: function () {
  62245. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62246. },
  62247. enumerable: true,
  62248. configurable: true
  62249. });
  62250. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62251. get: function () {
  62252. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62253. },
  62254. enumerable: true,
  62255. configurable: true
  62256. });
  62257. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62258. get: function () {
  62259. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62260. },
  62261. enumerable: true,
  62262. configurable: true
  62263. });
  62264. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62265. set: function (callback) {
  62266. if (this._onAfterUnbindObserver) {
  62267. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62268. }
  62269. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62270. },
  62271. enumerable: true,
  62272. configurable: true
  62273. });
  62274. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62275. set: function (callback) {
  62276. if (this._onBeforeRenderObserver) {
  62277. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62278. }
  62279. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62280. },
  62281. enumerable: true,
  62282. configurable: true
  62283. });
  62284. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62285. set: function (callback) {
  62286. if (this._onAfterRenderObserver) {
  62287. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62288. }
  62289. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62290. },
  62291. enumerable: true,
  62292. configurable: true
  62293. });
  62294. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62295. set: function (callback) {
  62296. if (this._onClearObserver) {
  62297. this.onClearObservable.remove(this._onClearObserver);
  62298. }
  62299. this._onClearObserver = this.onClearObservable.add(callback);
  62300. },
  62301. enumerable: true,
  62302. configurable: true
  62303. });
  62304. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62305. get: function () {
  62306. return this._renderTargetOptions;
  62307. },
  62308. enumerable: true,
  62309. configurable: true
  62310. });
  62311. RenderTargetTexture.prototype._onRatioRescale = function () {
  62312. if (this._sizeRatio) {
  62313. this.resize(this._initialSizeParameter);
  62314. }
  62315. };
  62316. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62317. get: function () {
  62318. return this._boundingBoxSize;
  62319. },
  62320. /**
  62321. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62322. * When defined, the cubemap will switch to local mode
  62323. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62324. * @example https://www.babylonjs-playground.com/#RNASML
  62325. */
  62326. set: function (value) {
  62327. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62328. return;
  62329. }
  62330. this._boundingBoxSize = value;
  62331. var scene = this.getScene();
  62332. if (scene) {
  62333. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62334. }
  62335. },
  62336. enumerable: true,
  62337. configurable: true
  62338. });
  62339. /**
  62340. * Creates a depth stencil texture.
  62341. * This is only available in WebGL 2 or with the depth texture extension available.
  62342. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62343. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62344. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62345. */
  62346. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62347. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62348. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62349. if (generateStencil === void 0) { generateStencil = false; }
  62350. if (!this.getScene()) {
  62351. return;
  62352. }
  62353. var engine = this.getScene().getEngine();
  62354. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62355. bilinearFiltering: bilinearFiltering,
  62356. comparisonFunction: comparisonFunction,
  62357. generateStencil: generateStencil,
  62358. isCube: this.isCube
  62359. });
  62360. engine.setFrameBufferDepthStencilTexture(this);
  62361. };
  62362. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62363. if (size.ratio) {
  62364. this._sizeRatio = size.ratio;
  62365. this._size = {
  62366. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62367. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62368. };
  62369. }
  62370. else {
  62371. this._size = size;
  62372. }
  62373. };
  62374. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62375. get: function () {
  62376. return this._samples;
  62377. },
  62378. set: function (value) {
  62379. if (this._samples === value) {
  62380. return;
  62381. }
  62382. var scene = this.getScene();
  62383. if (!scene) {
  62384. return;
  62385. }
  62386. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62387. },
  62388. enumerable: true,
  62389. configurable: true
  62390. });
  62391. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62392. this._currentRefreshId = -1;
  62393. };
  62394. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62395. get: function () {
  62396. return this._refreshRate;
  62397. },
  62398. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62399. set: function (value) {
  62400. this._refreshRate = value;
  62401. this.resetRefreshCounter();
  62402. },
  62403. enumerable: true,
  62404. configurable: true
  62405. });
  62406. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62407. if (!this._postProcessManager) {
  62408. var scene = this.getScene();
  62409. if (!scene) {
  62410. return;
  62411. }
  62412. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62413. this._postProcesses = new Array();
  62414. }
  62415. this._postProcesses.push(postProcess);
  62416. this._postProcesses[0].autoClear = false;
  62417. };
  62418. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62419. if (!this._postProcesses) {
  62420. return;
  62421. }
  62422. if (dispose) {
  62423. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62424. var postProcess = _a[_i];
  62425. postProcess.dispose();
  62426. }
  62427. }
  62428. this._postProcesses = [];
  62429. };
  62430. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62431. if (!this._postProcesses) {
  62432. return;
  62433. }
  62434. var index = this._postProcesses.indexOf(postProcess);
  62435. if (index === -1) {
  62436. return;
  62437. }
  62438. this._postProcesses.splice(index, 1);
  62439. if (this._postProcesses.length > 0) {
  62440. this._postProcesses[0].autoClear = false;
  62441. }
  62442. };
  62443. RenderTargetTexture.prototype._shouldRender = function () {
  62444. if (this._currentRefreshId === -1) { // At least render once
  62445. this._currentRefreshId = 1;
  62446. return true;
  62447. }
  62448. if (this.refreshRate === this._currentRefreshId) {
  62449. this._currentRefreshId = 1;
  62450. return true;
  62451. }
  62452. this._currentRefreshId++;
  62453. return false;
  62454. };
  62455. RenderTargetTexture.prototype.getRenderSize = function () {
  62456. if (this._size.width) {
  62457. return this._size.width;
  62458. }
  62459. return this._size;
  62460. };
  62461. RenderTargetTexture.prototype.getRenderWidth = function () {
  62462. if (this._size.width) {
  62463. return this._size.width;
  62464. }
  62465. return this._size;
  62466. };
  62467. RenderTargetTexture.prototype.getRenderHeight = function () {
  62468. if (this._size.width) {
  62469. return this._size.height;
  62470. }
  62471. return this._size;
  62472. };
  62473. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62474. get: function () {
  62475. return true;
  62476. },
  62477. enumerable: true,
  62478. configurable: true
  62479. });
  62480. RenderTargetTexture.prototype.scale = function (ratio) {
  62481. var newSize = this.getRenderSize() * ratio;
  62482. this.resize(newSize);
  62483. };
  62484. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62485. if (this.isCube) {
  62486. return this._textureMatrix;
  62487. }
  62488. return _super.prototype.getReflectionTextureMatrix.call(this);
  62489. };
  62490. RenderTargetTexture.prototype.resize = function (size) {
  62491. this.releaseInternalTexture();
  62492. var scene = this.getScene();
  62493. if (!scene) {
  62494. return;
  62495. }
  62496. this._processSizeParameter(size);
  62497. if (this.isCube) {
  62498. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62499. }
  62500. else {
  62501. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62502. }
  62503. };
  62504. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62505. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62506. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62507. var scene = this.getScene();
  62508. if (!scene) {
  62509. return;
  62510. }
  62511. var engine = scene.getEngine();
  62512. if (this.useCameraPostProcesses !== undefined) {
  62513. useCameraPostProcess = this.useCameraPostProcesses;
  62514. }
  62515. if (this._waitingRenderList) {
  62516. this.renderList = [];
  62517. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62518. var id = this._waitingRenderList[index];
  62519. var mesh_1 = scene.getMeshByID(id);
  62520. if (mesh_1) {
  62521. this.renderList.push(mesh_1);
  62522. }
  62523. }
  62524. delete this._waitingRenderList;
  62525. }
  62526. // Is predicate defined?
  62527. if (this.renderListPredicate) {
  62528. if (this.renderList) {
  62529. this.renderList.splice(0); // Clear previous renderList
  62530. }
  62531. else {
  62532. this.renderList = [];
  62533. }
  62534. var scene = this.getScene();
  62535. if (!scene) {
  62536. return;
  62537. }
  62538. var sceneMeshes = scene.meshes;
  62539. for (var index = 0; index < sceneMeshes.length; index++) {
  62540. var mesh = sceneMeshes[index];
  62541. if (this.renderListPredicate(mesh)) {
  62542. this.renderList.push(mesh);
  62543. }
  62544. }
  62545. }
  62546. this.onBeforeBindObservable.notifyObservers(this);
  62547. // Set custom projection.
  62548. // Needs to be before binding to prevent changing the aspect ratio.
  62549. var camera;
  62550. if (this.activeCamera) {
  62551. camera = this.activeCamera;
  62552. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62553. if (this.activeCamera !== scene.activeCamera) {
  62554. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62555. }
  62556. }
  62557. else {
  62558. camera = scene.activeCamera;
  62559. if (camera) {
  62560. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62561. }
  62562. }
  62563. // Prepare renderingManager
  62564. this._renderingManager.reset();
  62565. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62566. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62567. var sceneRenderId = scene.getRenderId();
  62568. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62569. var mesh = currentRenderList[meshIndex];
  62570. if (mesh) {
  62571. if (!mesh.isReady(this.refreshRate === 0)) {
  62572. this.resetRefreshCounter();
  62573. continue;
  62574. }
  62575. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62576. var isMasked = void 0;
  62577. if (!this.renderList && camera) {
  62578. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62579. }
  62580. else {
  62581. isMasked = false;
  62582. }
  62583. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62584. mesh._activate(sceneRenderId);
  62585. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62586. var subMesh = mesh.subMeshes[subIndex];
  62587. scene._activeIndices.addCount(subMesh.indexCount, false);
  62588. this._renderingManager.dispatch(subMesh, mesh);
  62589. }
  62590. }
  62591. }
  62592. }
  62593. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62594. var particleSystem = scene.particleSystems[particleIndex];
  62595. var emitter = particleSystem.emitter;
  62596. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62597. continue;
  62598. }
  62599. if (currentRenderList.indexOf(emitter) >= 0) {
  62600. this._renderingManager.dispatchParticles(particleSystem);
  62601. }
  62602. }
  62603. if (this.isCube) {
  62604. for (var face = 0; face < 6; face++) {
  62605. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62606. scene.incrementRenderId();
  62607. scene.resetCachedMaterial();
  62608. }
  62609. }
  62610. else {
  62611. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62612. }
  62613. this.onAfterUnbindObservable.notifyObservers(this);
  62614. if (scene.activeCamera) {
  62615. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62616. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62617. }
  62618. engine.setViewport(scene.activeCamera.viewport);
  62619. }
  62620. scene.resetCachedMaterial();
  62621. };
  62622. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62623. var minimum = 128;
  62624. var x = renderDimension * scale;
  62625. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62626. // Ensure we don't exceed the render dimension (while staying POT)
  62627. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62628. };
  62629. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62630. var _this = this;
  62631. if (!this._texture) {
  62632. return;
  62633. }
  62634. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62635. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62636. });
  62637. };
  62638. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62639. var scene = this.getScene();
  62640. if (!scene) {
  62641. return;
  62642. }
  62643. var engine = scene.getEngine();
  62644. if (!this._texture) {
  62645. return;
  62646. }
  62647. // Bind
  62648. if (this._postProcessManager) {
  62649. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62650. }
  62651. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62652. if (this._texture) {
  62653. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62654. }
  62655. }
  62656. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62657. // Clear
  62658. if (this.onClearObservable.hasObservers()) {
  62659. this.onClearObservable.notifyObservers(engine);
  62660. }
  62661. else {
  62662. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62663. }
  62664. if (!this._doNotChangeAspectRatio) {
  62665. scene.updateTransformMatrix(true);
  62666. }
  62667. // Render
  62668. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62669. if (this._postProcessManager) {
  62670. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62671. }
  62672. else if (useCameraPostProcess) {
  62673. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62674. }
  62675. if (!this._doNotChangeAspectRatio) {
  62676. scene.updateTransformMatrix(true);
  62677. }
  62678. // Dump ?
  62679. if (dumpForDebug) {
  62680. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62681. }
  62682. // Unbind
  62683. if (!this.isCube || faceIndex === 5) {
  62684. if (this.isCube) {
  62685. if (faceIndex === 5) {
  62686. engine.generateMipMapsForCubemap(this._texture);
  62687. }
  62688. }
  62689. this.unbindFrameBuffer(engine, faceIndex);
  62690. }
  62691. else {
  62692. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62693. }
  62694. };
  62695. /**
  62696. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62697. * This allowed control for front to back rendering or reversly depending of the special needs.
  62698. *
  62699. * @param renderingGroupId The rendering group id corresponding to its index
  62700. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62701. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62702. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62703. */
  62704. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62705. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62706. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62707. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62708. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62709. };
  62710. /**
  62711. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62712. *
  62713. * @param renderingGroupId The rendering group id corresponding to its index
  62714. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62715. */
  62716. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62717. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62718. };
  62719. RenderTargetTexture.prototype.clone = function () {
  62720. var textureSize = this.getSize();
  62721. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  62722. // Base texture
  62723. newTexture.hasAlpha = this.hasAlpha;
  62724. newTexture.level = this.level;
  62725. // RenderTarget Texture
  62726. newTexture.coordinatesMode = this.coordinatesMode;
  62727. if (this.renderList) {
  62728. newTexture.renderList = this.renderList.slice(0);
  62729. }
  62730. return newTexture;
  62731. };
  62732. RenderTargetTexture.prototype.serialize = function () {
  62733. if (!this.name) {
  62734. return null;
  62735. }
  62736. var serializationObject = _super.prototype.serialize.call(this);
  62737. serializationObject.renderTargetSize = this.getRenderSize();
  62738. serializationObject.renderList = [];
  62739. if (this.renderList) {
  62740. for (var index = 0; index < this.renderList.length; index++) {
  62741. serializationObject.renderList.push(this.renderList[index].id);
  62742. }
  62743. }
  62744. return serializationObject;
  62745. };
  62746. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62747. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62748. var objBuffer = this.getInternalTexture();
  62749. var scene = this.getScene();
  62750. if (objBuffer && scene) {
  62751. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62752. }
  62753. };
  62754. RenderTargetTexture.prototype.dispose = function () {
  62755. if (this._postProcessManager) {
  62756. this._postProcessManager.dispose();
  62757. this._postProcessManager = null;
  62758. }
  62759. this.clearPostProcesses(true);
  62760. if (this._resizeObserver) {
  62761. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62762. this._resizeObserver = null;
  62763. }
  62764. this.renderList = null;
  62765. // Remove from custom render targets
  62766. var scene = this.getScene();
  62767. if (!scene) {
  62768. return;
  62769. }
  62770. var index = scene.customRenderTargets.indexOf(this);
  62771. if (index >= 0) {
  62772. scene.customRenderTargets.splice(index, 1);
  62773. }
  62774. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62775. var camera = _a[_i];
  62776. index = camera.customRenderTargets.indexOf(this);
  62777. if (index >= 0) {
  62778. camera.customRenderTargets.splice(index, 1);
  62779. }
  62780. }
  62781. _super.prototype.dispose.call(this);
  62782. };
  62783. RenderTargetTexture.prototype._rebuild = function () {
  62784. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62785. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62786. }
  62787. if (this._postProcessManager) {
  62788. this._postProcessManager._rebuild();
  62789. }
  62790. };
  62791. /**
  62792. * Clear the info related to rendering groups preventing retention point in material dispose.
  62793. */
  62794. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62795. if (this._renderingManager) {
  62796. this._renderingManager.freeRenderingGroups();
  62797. }
  62798. };
  62799. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62800. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62801. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62802. return RenderTargetTexture;
  62803. }(BABYLON.Texture));
  62804. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62805. })(BABYLON || (BABYLON = {}));
  62806. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62807. var BABYLON;
  62808. (function (BABYLON) {
  62809. ;
  62810. var MultiRenderTarget = /** @class */ (function (_super) {
  62811. __extends(MultiRenderTarget, _super);
  62812. function MultiRenderTarget(name, size, count, scene, options) {
  62813. var _this = this;
  62814. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62815. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62816. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62817. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62818. _this._engine = scene.getEngine();
  62819. if (!_this.isSupported) {
  62820. _this.dispose();
  62821. return;
  62822. }
  62823. var types = [];
  62824. var samplingModes = [];
  62825. for (var i = 0; i < count; i++) {
  62826. if (options && options.types && options.types[i] !== undefined) {
  62827. types.push(options.types[i]);
  62828. }
  62829. else {
  62830. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62831. }
  62832. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62833. samplingModes.push(options.samplingModes[i]);
  62834. }
  62835. else {
  62836. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62837. }
  62838. }
  62839. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62840. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62841. _this._size = size;
  62842. _this._multiRenderTargetOptions = {
  62843. samplingModes: samplingModes,
  62844. generateMipMaps: generateMipMaps,
  62845. generateDepthBuffer: generateDepthBuffer,
  62846. generateStencilBuffer: generateStencilBuffer,
  62847. generateDepthTexture: generateDepthTexture,
  62848. types: types,
  62849. textureCount: count
  62850. };
  62851. _this._createInternalTextures();
  62852. _this._createTextures();
  62853. return _this;
  62854. }
  62855. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62856. get: function () {
  62857. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62858. },
  62859. enumerable: true,
  62860. configurable: true
  62861. });
  62862. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62863. get: function () {
  62864. return this._textures;
  62865. },
  62866. enumerable: true,
  62867. configurable: true
  62868. });
  62869. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62870. get: function () {
  62871. return this._textures[this._textures.length - 1];
  62872. },
  62873. enumerable: true,
  62874. configurable: true
  62875. });
  62876. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62877. set: function (wrap) {
  62878. if (this._textures) {
  62879. for (var i = 0; i < this._textures.length; i++) {
  62880. this._textures[i].wrapU = wrap;
  62881. }
  62882. }
  62883. },
  62884. enumerable: true,
  62885. configurable: true
  62886. });
  62887. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62888. set: function (wrap) {
  62889. if (this._textures) {
  62890. for (var i = 0; i < this._textures.length; i++) {
  62891. this._textures[i].wrapV = wrap;
  62892. }
  62893. }
  62894. },
  62895. enumerable: true,
  62896. configurable: true
  62897. });
  62898. MultiRenderTarget.prototype._rebuild = function () {
  62899. this.releaseInternalTextures();
  62900. this._createInternalTextures();
  62901. for (var i = 0; i < this._internalTextures.length; i++) {
  62902. var texture = this._textures[i];
  62903. texture._texture = this._internalTextures[i];
  62904. }
  62905. // Keeps references to frame buffer and stencil/depth buffer
  62906. this._texture = this._internalTextures[0];
  62907. };
  62908. MultiRenderTarget.prototype._createInternalTextures = function () {
  62909. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62910. };
  62911. MultiRenderTarget.prototype._createTextures = function () {
  62912. this._textures = [];
  62913. for (var i = 0; i < this._internalTextures.length; i++) {
  62914. var texture = new BABYLON.Texture(null, this.getScene());
  62915. texture._texture = this._internalTextures[i];
  62916. this._textures.push(texture);
  62917. }
  62918. // Keeps references to frame buffer and stencil/depth buffer
  62919. this._texture = this._internalTextures[0];
  62920. };
  62921. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62922. get: function () {
  62923. return this._samples;
  62924. },
  62925. set: function (value) {
  62926. if (this._samples === value) {
  62927. return;
  62928. }
  62929. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62930. },
  62931. enumerable: true,
  62932. configurable: true
  62933. });
  62934. MultiRenderTarget.prototype.resize = function (size) {
  62935. this.releaseInternalTextures();
  62936. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62937. this._createInternalTextures();
  62938. };
  62939. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62940. var _this = this;
  62941. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62942. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62943. });
  62944. };
  62945. MultiRenderTarget.prototype.dispose = function () {
  62946. this.releaseInternalTextures();
  62947. _super.prototype.dispose.call(this);
  62948. };
  62949. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62950. if (!this._internalTextures) {
  62951. return;
  62952. }
  62953. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62954. if (this._internalTextures[i] !== undefined) {
  62955. this._internalTextures[i].dispose();
  62956. this._internalTextures.splice(i, 1);
  62957. }
  62958. }
  62959. };
  62960. return MultiRenderTarget;
  62961. }(BABYLON.RenderTargetTexture));
  62962. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62963. })(BABYLON || (BABYLON = {}));
  62964. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62965. var BABYLON;
  62966. (function (BABYLON) {
  62967. var MirrorTexture = /** @class */ (function (_super) {
  62968. __extends(MirrorTexture, _super);
  62969. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62970. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62972. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62973. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62974. _this.scene = scene;
  62975. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62976. _this._transformMatrix = BABYLON.Matrix.Zero();
  62977. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62978. _this._adaptiveBlurKernel = 0;
  62979. _this._blurKernelX = 0;
  62980. _this._blurKernelY = 0;
  62981. _this._blurRatio = 1.0;
  62982. _this.ignoreCameraViewport = true;
  62983. _this._updateGammaSpace();
  62984. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  62985. _this._updateGammaSpace;
  62986. });
  62987. _this.onBeforeRenderObservable.add(function () {
  62988. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62989. _this._savedViewMatrix = scene.getViewMatrix();
  62990. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62991. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62992. scene.clipPlane = _this.mirrorPlane;
  62993. scene.getEngine().cullBackFaces = false;
  62994. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62995. });
  62996. _this.onAfterRenderObservable.add(function () {
  62997. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62998. scene.getEngine().cullBackFaces = true;
  62999. scene._mirroredCameraPosition = null;
  63000. delete scene.clipPlane;
  63001. });
  63002. return _this;
  63003. }
  63004. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63005. get: function () {
  63006. return this._blurRatio;
  63007. },
  63008. set: function (value) {
  63009. if (this._blurRatio === value) {
  63010. return;
  63011. }
  63012. this._blurRatio = value;
  63013. this._preparePostProcesses();
  63014. },
  63015. enumerable: true,
  63016. configurable: true
  63017. });
  63018. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63019. set: function (value) {
  63020. this._adaptiveBlurKernel = value;
  63021. this._autoComputeBlurKernel();
  63022. },
  63023. enumerable: true,
  63024. configurable: true
  63025. });
  63026. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63027. set: function (value) {
  63028. this.blurKernelX = value;
  63029. this.blurKernelY = value;
  63030. },
  63031. enumerable: true,
  63032. configurable: true
  63033. });
  63034. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63035. get: function () {
  63036. return this._blurKernelX;
  63037. },
  63038. set: function (value) {
  63039. if (this._blurKernelX === value) {
  63040. return;
  63041. }
  63042. this._blurKernelX = value;
  63043. this._preparePostProcesses();
  63044. },
  63045. enumerable: true,
  63046. configurable: true
  63047. });
  63048. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63049. get: function () {
  63050. return this._blurKernelY;
  63051. },
  63052. set: function (value) {
  63053. if (this._blurKernelY === value) {
  63054. return;
  63055. }
  63056. this._blurKernelY = value;
  63057. this._preparePostProcesses();
  63058. },
  63059. enumerable: true,
  63060. configurable: true
  63061. });
  63062. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63063. var engine = this.getScene().getEngine();
  63064. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63065. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63066. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63067. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63068. };
  63069. MirrorTexture.prototype._onRatioRescale = function () {
  63070. if (this._sizeRatio) {
  63071. this.resize(this._initialSizeParameter);
  63072. if (!this._adaptiveBlurKernel) {
  63073. this._preparePostProcesses();
  63074. }
  63075. }
  63076. if (this._adaptiveBlurKernel) {
  63077. this._autoComputeBlurKernel();
  63078. }
  63079. };
  63080. MirrorTexture.prototype._updateGammaSpace = function () {
  63081. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63082. };
  63083. MirrorTexture.prototype._preparePostProcesses = function () {
  63084. this.clearPostProcesses(true);
  63085. if (this._blurKernelX && this._blurKernelY) {
  63086. var engine = this.getScene().getEngine();
  63087. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63088. 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);
  63089. this._blurX.autoClear = false;
  63090. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63091. this._blurX.inputTexture = this._texture;
  63092. }
  63093. else {
  63094. this._blurX.alwaysForcePOT = true;
  63095. }
  63096. 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);
  63097. this._blurY.autoClear = false;
  63098. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63099. this.addPostProcess(this._blurX);
  63100. this.addPostProcess(this._blurY);
  63101. }
  63102. else {
  63103. if (this._blurY) {
  63104. this.removePostProcess(this._blurY);
  63105. this._blurY.dispose();
  63106. this._blurY = null;
  63107. }
  63108. if (this._blurX) {
  63109. this.removePostProcess(this._blurX);
  63110. this._blurX.dispose();
  63111. this._blurX = null;
  63112. }
  63113. }
  63114. };
  63115. MirrorTexture.prototype.clone = function () {
  63116. var scene = this.getScene();
  63117. if (!scene) {
  63118. return this;
  63119. }
  63120. var textureSize = this.getSize();
  63121. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63122. // Base texture
  63123. newTexture.hasAlpha = this.hasAlpha;
  63124. newTexture.level = this.level;
  63125. // Mirror Texture
  63126. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63127. if (this.renderList) {
  63128. newTexture.renderList = this.renderList.slice(0);
  63129. }
  63130. return newTexture;
  63131. };
  63132. MirrorTexture.prototype.serialize = function () {
  63133. if (!this.name) {
  63134. return null;
  63135. }
  63136. var serializationObject = _super.prototype.serialize.call(this);
  63137. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63138. return serializationObject;
  63139. };
  63140. MirrorTexture.prototype.dispose = function () {
  63141. _super.prototype.dispose.call(this);
  63142. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63143. };
  63144. return MirrorTexture;
  63145. }(BABYLON.RenderTargetTexture));
  63146. BABYLON.MirrorTexture = MirrorTexture;
  63147. })(BABYLON || (BABYLON = {}));
  63148. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63149. var BABYLON;
  63150. (function (BABYLON) {
  63151. /**
  63152. * Creates a refraction texture used by refraction channel of the standard material.
  63153. * @param name the texture name
  63154. * @param size size of the underlying texture
  63155. * @param scene root scene
  63156. */
  63157. var RefractionTexture = /** @class */ (function (_super) {
  63158. __extends(RefractionTexture, _super);
  63159. function RefractionTexture(name, size, scene, generateMipMaps) {
  63160. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63161. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63162. _this.depth = 2.0;
  63163. _this.onBeforeRenderObservable.add(function () {
  63164. scene.clipPlane = _this.refractionPlane;
  63165. });
  63166. _this.onAfterRenderObservable.add(function () {
  63167. delete scene.clipPlane;
  63168. });
  63169. return _this;
  63170. }
  63171. RefractionTexture.prototype.clone = function () {
  63172. var scene = this.getScene();
  63173. if (!scene) {
  63174. return this;
  63175. }
  63176. var textureSize = this.getSize();
  63177. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63178. // Base texture
  63179. newTexture.hasAlpha = this.hasAlpha;
  63180. newTexture.level = this.level;
  63181. // Refraction Texture
  63182. newTexture.refractionPlane = this.refractionPlane.clone();
  63183. if (this.renderList) {
  63184. newTexture.renderList = this.renderList.slice(0);
  63185. }
  63186. newTexture.depth = this.depth;
  63187. return newTexture;
  63188. };
  63189. RefractionTexture.prototype.serialize = function () {
  63190. if (!this.name) {
  63191. return null;
  63192. }
  63193. var serializationObject = _super.prototype.serialize.call(this);
  63194. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63195. serializationObject.depth = this.depth;
  63196. return serializationObject;
  63197. };
  63198. return RefractionTexture;
  63199. }(BABYLON.RenderTargetTexture));
  63200. BABYLON.RefractionTexture = RefractionTexture;
  63201. })(BABYLON || (BABYLON = {}));
  63202. //# sourceMappingURL=babylon.refractionTexture.js.map
  63203. var BABYLON;
  63204. (function (BABYLON) {
  63205. /**
  63206. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63207. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63208. */
  63209. var DynamicTexture = /** @class */ (function (_super) {
  63210. __extends(DynamicTexture, _super);
  63211. /**
  63212. * Creates a {BABYLON.DynamicTexture}
  63213. * @param name defines the name of the texture
  63214. * @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
  63215. * @param scene defines the scene where you want the texture
  63216. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63217. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63218. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63219. */
  63220. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63221. if (scene === void 0) { scene = null; }
  63222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63223. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63224. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63225. _this.name = name;
  63226. _this._engine = _this.getScene().getEngine();
  63227. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63228. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63229. _this._generateMipMaps = generateMipMaps;
  63230. if (options.getContext) {
  63231. _this._canvas = options;
  63232. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63233. }
  63234. else {
  63235. _this._canvas = document.createElement("canvas");
  63236. if (options.width) {
  63237. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63238. }
  63239. else {
  63240. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63241. }
  63242. }
  63243. var textureSize = _this.getSize();
  63244. _this._canvas.width = textureSize.width;
  63245. _this._canvas.height = textureSize.height;
  63246. _this._context = _this._canvas.getContext("2d");
  63247. return _this;
  63248. }
  63249. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63250. /**
  63251. * Gets the current state of canRescale
  63252. */
  63253. get: function () {
  63254. return true;
  63255. },
  63256. enumerable: true,
  63257. configurable: true
  63258. });
  63259. DynamicTexture.prototype._recreate = function (textureSize) {
  63260. this._canvas.width = textureSize.width;
  63261. this._canvas.height = textureSize.height;
  63262. this.releaseInternalTexture();
  63263. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63264. };
  63265. /**
  63266. * Scales the texture
  63267. * @param ratio the scale factor to apply to both width and height
  63268. */
  63269. DynamicTexture.prototype.scale = function (ratio) {
  63270. var textureSize = this.getSize();
  63271. textureSize.width *= ratio;
  63272. textureSize.height *= ratio;
  63273. this._recreate(textureSize);
  63274. };
  63275. /**
  63276. * Resizes the texture
  63277. * @param width the new width
  63278. * @param height the new height
  63279. */
  63280. DynamicTexture.prototype.scaleTo = function (width, height) {
  63281. var textureSize = this.getSize();
  63282. textureSize.width = width;
  63283. textureSize.height = height;
  63284. this._recreate(textureSize);
  63285. };
  63286. /**
  63287. * Gets the context of the canvas used by the texture
  63288. * @returns the canvas context of the dynamic texture
  63289. */
  63290. DynamicTexture.prototype.getContext = function () {
  63291. return this._context;
  63292. };
  63293. /**
  63294. * Clears the texture
  63295. */
  63296. DynamicTexture.prototype.clear = function () {
  63297. var size = this.getSize();
  63298. this._context.fillRect(0, 0, size.width, size.height);
  63299. };
  63300. /**
  63301. * Updates the texture
  63302. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63303. */
  63304. DynamicTexture.prototype.update = function (invertY) {
  63305. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63306. };
  63307. /**
  63308. * Draws text onto the texture
  63309. * @param text defines the text to be drawn
  63310. * @param x defines the placement of the text from the left
  63311. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63312. * @param font defines the font to be used with font-style, font-size, font-name
  63313. * @param color defines the color used for the text
  63314. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63315. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63316. * @param update defines whether texture is immediately update (default is true)
  63317. */
  63318. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63319. if (update === void 0) { update = true; }
  63320. var size = this.getSize();
  63321. if (clearColor) {
  63322. this._context.fillStyle = clearColor;
  63323. this._context.fillRect(0, 0, size.width, size.height);
  63324. }
  63325. this._context.font = font;
  63326. if (x === null || x === undefined) {
  63327. var textSize = this._context.measureText(text);
  63328. x = (size.width - textSize.width) / 2;
  63329. }
  63330. if (y === null || y === undefined) {
  63331. var fontSize = parseInt((font.replace(/\D/g, '')));
  63332. ;
  63333. y = (size.height / 2) + (fontSize / 3.65);
  63334. }
  63335. this._context.fillStyle = color;
  63336. this._context.fillText(text, x, y);
  63337. if (update) {
  63338. this.update(invertY);
  63339. }
  63340. };
  63341. /**
  63342. * Clones the texture
  63343. * @returns the clone of the texture.
  63344. */
  63345. DynamicTexture.prototype.clone = function () {
  63346. var scene = this.getScene();
  63347. if (!scene) {
  63348. return this;
  63349. }
  63350. var textureSize = this.getSize();
  63351. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63352. // Base texture
  63353. newTexture.hasAlpha = this.hasAlpha;
  63354. newTexture.level = this.level;
  63355. // Dynamic Texture
  63356. newTexture.wrapU = this.wrapU;
  63357. newTexture.wrapV = this.wrapV;
  63358. return newTexture;
  63359. };
  63360. /** @ignore */
  63361. DynamicTexture.prototype._rebuild = function () {
  63362. this.update();
  63363. };
  63364. return DynamicTexture;
  63365. }(BABYLON.Texture));
  63366. BABYLON.DynamicTexture = DynamicTexture;
  63367. })(BABYLON || (BABYLON = {}));
  63368. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63369. var BABYLON;
  63370. (function (BABYLON) {
  63371. var VideoTexture = /** @class */ (function (_super) {
  63372. __extends(VideoTexture, _super);
  63373. /**
  63374. * Creates a video texture.
  63375. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63376. * @param {string | null} name optional name, will detect from video source, if not defined
  63377. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63378. * @param {BABYLON.Scene} scene is obviously the current scene.
  63379. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63380. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63381. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63382. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63383. */
  63384. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63385. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63386. if (invertY === void 0) { invertY = false; }
  63387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63388. if (settings === void 0) { settings = {
  63389. autoPlay: true,
  63390. loop: true,
  63391. autoUpdateTexture: true,
  63392. }; }
  63393. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63394. _this._createInternalTexture = function () {
  63395. if (_this._texture != null) {
  63396. return;
  63397. }
  63398. if (!_this._engine.needPOTTextures ||
  63399. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63400. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63401. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63402. }
  63403. else {
  63404. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63405. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63406. _this._generateMipMaps = false;
  63407. }
  63408. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63409. _this._texture.isReady = true;
  63410. _this._updateInternalTexture();
  63411. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63412. _this.onLoadObservable.notifyObservers(_this);
  63413. }
  63414. };
  63415. _this.reset = function () {
  63416. if (_this._texture == null) {
  63417. return;
  63418. }
  63419. _this._texture.dispose();
  63420. _this._texture = null;
  63421. };
  63422. _this._updateInternalTexture = function (e) {
  63423. if (_this._texture == null || !_this._texture.isReady) {
  63424. return;
  63425. }
  63426. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63427. return;
  63428. }
  63429. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63430. };
  63431. _this._engine = _this.getScene().getEngine();
  63432. _this._generateMipMaps = generateMipMaps;
  63433. _this._samplingMode = samplingMode;
  63434. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63435. _this.name = name || _this._getName(src);
  63436. _this.video = _this._getVideo(src);
  63437. if (settings.autoPlay !== undefined) {
  63438. _this.video.autoplay = settings.autoPlay;
  63439. }
  63440. if (settings.loop !== undefined) {
  63441. _this.video.loop = settings.loop;
  63442. }
  63443. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63444. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63445. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63446. _this.video.addEventListener("emptied", _this.reset);
  63447. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63448. _this._createInternalTexture();
  63449. }
  63450. return _this;
  63451. }
  63452. VideoTexture.prototype._getName = function (src) {
  63453. if (src instanceof HTMLVideoElement) {
  63454. return src.currentSrc;
  63455. }
  63456. if (typeof src === "object") {
  63457. return src.toString();
  63458. }
  63459. return src;
  63460. };
  63461. ;
  63462. VideoTexture.prototype._getVideo = function (src) {
  63463. if (src instanceof HTMLVideoElement) {
  63464. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63465. return src;
  63466. }
  63467. var video = document.createElement("video");
  63468. if (typeof src === "string") {
  63469. BABYLON.Tools.SetCorsBehavior(src, video);
  63470. video.src = src;
  63471. }
  63472. else {
  63473. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63474. src.forEach(function (url) {
  63475. var source = document.createElement("source");
  63476. source.src = url;
  63477. video.appendChild(source);
  63478. });
  63479. }
  63480. return video;
  63481. };
  63482. ;
  63483. /**
  63484. * Internal method to initiate `update`.
  63485. */
  63486. VideoTexture.prototype._rebuild = function () {
  63487. this.update();
  63488. };
  63489. /**
  63490. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63491. */
  63492. VideoTexture.prototype.update = function () {
  63493. if (!this.autoUpdateTexture) {
  63494. // Expecting user to call `updateTexture` manually
  63495. return;
  63496. }
  63497. this.updateTexture(true);
  63498. };
  63499. /**
  63500. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63501. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63502. */
  63503. VideoTexture.prototype.updateTexture = function (isVisible) {
  63504. if (!isVisible) {
  63505. return;
  63506. }
  63507. if (this.video.paused) {
  63508. return;
  63509. }
  63510. this._updateInternalTexture();
  63511. };
  63512. /**
  63513. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63514. * @param url New url.
  63515. */
  63516. VideoTexture.prototype.updateURL = function (url) {
  63517. this.video.src = url;
  63518. };
  63519. VideoTexture.prototype.dispose = function () {
  63520. _super.prototype.dispose.call(this);
  63521. this.video.removeEventListener("canplay", this._createInternalTexture);
  63522. this.video.removeEventListener("paused", this._updateInternalTexture);
  63523. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63524. this.video.removeEventListener("emptied", this.reset);
  63525. this.video.pause();
  63526. };
  63527. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63528. var video = document.createElement("video");
  63529. var constraintsDeviceId;
  63530. if (constraints && constraints.deviceId) {
  63531. constraintsDeviceId = {
  63532. exact: constraints.deviceId,
  63533. };
  63534. }
  63535. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63536. if (navigator.mediaDevices) {
  63537. navigator.mediaDevices.getUserMedia({ video: constraints })
  63538. .then(function (stream) {
  63539. if (video.mozSrcObject !== undefined) {
  63540. // hack for Firefox < 19
  63541. video.mozSrcObject = stream;
  63542. }
  63543. else {
  63544. video.srcObject = stream;
  63545. }
  63546. var onPlaying = function () {
  63547. if (onReady) {
  63548. onReady(new VideoTexture("video", video, scene, true, true));
  63549. }
  63550. video.removeEventListener("playing", onPlaying);
  63551. };
  63552. video.addEventListener("playing", onPlaying);
  63553. video.play();
  63554. })
  63555. .catch(function (err) {
  63556. BABYLON.Tools.Error(err.name);
  63557. });
  63558. }
  63559. else {
  63560. navigator.getUserMedia =
  63561. navigator.getUserMedia ||
  63562. navigator.webkitGetUserMedia ||
  63563. navigator.mozGetUserMedia ||
  63564. navigator.msGetUserMedia;
  63565. if (navigator.getUserMedia) {
  63566. navigator.getUserMedia({
  63567. video: {
  63568. deviceId: constraintsDeviceId,
  63569. width: {
  63570. min: (constraints && constraints.minWidth) || 256,
  63571. max: (constraints && constraints.maxWidth) || 640,
  63572. },
  63573. height: {
  63574. min: (constraints && constraints.minHeight) || 256,
  63575. max: (constraints && constraints.maxHeight) || 480,
  63576. },
  63577. },
  63578. }, function (stream) {
  63579. if (video.mozSrcObject !== undefined) {
  63580. // hack for Firefox < 19
  63581. video.mozSrcObject = stream;
  63582. }
  63583. else {
  63584. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63585. }
  63586. video.play();
  63587. if (onReady) {
  63588. onReady(new VideoTexture("video", video, scene, true, true));
  63589. }
  63590. }, function (e) {
  63591. BABYLON.Tools.Error(e.name);
  63592. });
  63593. }
  63594. }
  63595. };
  63596. return VideoTexture;
  63597. }(BABYLON.Texture));
  63598. BABYLON.VideoTexture = VideoTexture;
  63599. })(BABYLON || (BABYLON = {}));
  63600. //# sourceMappingURL=babylon.videoTexture.js.map
  63601. var BABYLON;
  63602. (function (BABYLON) {
  63603. var RawTexture = /** @class */ (function (_super) {
  63604. __extends(RawTexture, _super);
  63605. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63606. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63607. if (invertY === void 0) { invertY = false; }
  63608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63609. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63610. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63611. _this.format = format;
  63612. _this._engine = scene.getEngine();
  63613. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63614. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63615. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63616. return _this;
  63617. }
  63618. RawTexture.prototype.update = function (data) {
  63619. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63620. };
  63621. // Statics
  63622. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63624. if (invertY === void 0) { invertY = false; }
  63625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63626. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63627. };
  63628. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63630. if (invertY === void 0) { invertY = false; }
  63631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63632. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63633. };
  63634. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63635. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63636. if (invertY === void 0) { invertY = false; }
  63637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63638. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63639. };
  63640. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63642. if (invertY === void 0) { invertY = false; }
  63643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63644. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63645. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63646. };
  63647. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63649. if (invertY === void 0) { invertY = false; }
  63650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63652. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63653. };
  63654. return RawTexture;
  63655. }(BABYLON.Texture));
  63656. BABYLON.RawTexture = RawTexture;
  63657. })(BABYLON || (BABYLON = {}));
  63658. //# sourceMappingURL=babylon.rawTexture.js.map
  63659. var BABYLON;
  63660. (function (BABYLON) {
  63661. /**
  63662. * Class used to store 3D textures containing user data
  63663. */
  63664. var RawTexture3D = /** @class */ (function (_super) {
  63665. __extends(RawTexture3D, _super);
  63666. /**
  63667. * Create a new RawTexture3D
  63668. * @param data defines the data of the texture
  63669. * @param width defines the width of the texture
  63670. * @param height defines the height of the texture
  63671. * @param depth defines the depth of the texture
  63672. * @param format defines the texture format to use
  63673. * @param scene defines the hosting scene
  63674. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63675. * @param invertY defines if texture must be stored with Y axis inverted
  63676. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63677. */
  63678. function RawTexture3D(data, width, height, depth,
  63679. /** Gets or sets the texture format to use*/
  63680. format, scene, generateMipMaps, invertY, samplingMode) {
  63681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63682. if (invertY === void 0) { invertY = false; }
  63683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63684. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63685. _this.format = format;
  63686. _this._engine = scene.getEngine();
  63687. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63688. _this.is3D = true;
  63689. return _this;
  63690. }
  63691. /**
  63692. * Update the texture with new data
  63693. * @param data defines the data to store in the texture
  63694. */
  63695. RawTexture3D.prototype.update = function (data) {
  63696. if (!this._texture) {
  63697. return;
  63698. }
  63699. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63700. };
  63701. return RawTexture3D;
  63702. }(BABYLON.Texture));
  63703. BABYLON.RawTexture3D = RawTexture3D;
  63704. })(BABYLON || (BABYLON = {}));
  63705. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63706. var BABYLON;
  63707. (function (BABYLON) {
  63708. /**
  63709. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63710. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63711. */
  63712. var PostProcess = /** @class */ (function () {
  63713. /**
  63714. * Creates a new instance PostProcess
  63715. * @param name The name of the PostProcess.
  63716. * @param fragmentUrl The url of the fragment shader to be used.
  63717. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63718. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63719. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63720. * @param camera The camera to apply the render pass to.
  63721. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63722. * @param engine The engine which the post process will be applied. (default: current engine)
  63723. * @param reusable If the post process can be reused on the same frame. (default: false)
  63724. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63725. * @param textureType Type of textures used when performing the post process. (default: 0)
  63726. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63727. * @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
  63728. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63729. */
  63730. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63732. if (defines === void 0) { defines = null; }
  63733. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63734. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63735. if (blockCompilation === void 0) { blockCompilation = false; }
  63736. this.name = name;
  63737. /**
  63738. * Width of the texture to apply the post process on
  63739. */
  63740. this.width = -1;
  63741. /**
  63742. * Height of the texture to apply the post process on
  63743. */
  63744. this.height = -1;
  63745. /**
  63746. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63747. */
  63748. this._outputTexture = null;
  63749. /**
  63750. * If the buffer needs to be cleared before applying the post process. (default: true)
  63751. * Should be set to false if shader will overwrite all previous pixels.
  63752. */
  63753. this.autoClear = true;
  63754. /**
  63755. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63756. */
  63757. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63758. /**
  63759. * Animations to be used for the post processing
  63760. */
  63761. this.animations = new Array();
  63762. /**
  63763. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63764. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63765. */
  63766. this.enablePixelPerfectMode = false;
  63767. /**
  63768. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63769. */
  63770. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63771. /**
  63772. * Force textures to be a power of two (default: false)
  63773. */
  63774. this.alwaysForcePOT = false;
  63775. /**
  63776. * Number of sample textures (default: 1)
  63777. */
  63778. this.samples = 1;
  63779. /**
  63780. * Modify the scale of the post process to be the same as the viewport (default: false)
  63781. */
  63782. this.adaptScaleToCurrentViewport = false;
  63783. this._reusable = false;
  63784. /**
  63785. * Smart array of input and output textures for the post process.
  63786. */
  63787. this._textures = new BABYLON.SmartArray(2);
  63788. /**
  63789. * The index in _textures that corresponds to the output texture.
  63790. */
  63791. this._currentRenderTextureInd = 0;
  63792. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63793. this._texelSize = BABYLON.Vector2.Zero();
  63794. // Events
  63795. /**
  63796. * An event triggered when the postprocess is activated.
  63797. */
  63798. this.onActivateObservable = new BABYLON.Observable();
  63799. /**
  63800. * An event triggered when the postprocess changes its size.
  63801. */
  63802. this.onSizeChangedObservable = new BABYLON.Observable();
  63803. /**
  63804. * An event triggered when the postprocess applies its effect.
  63805. */
  63806. this.onApplyObservable = new BABYLON.Observable();
  63807. /**
  63808. * An event triggered before rendering the postprocess
  63809. */
  63810. this.onBeforeRenderObservable = new BABYLON.Observable();
  63811. /**
  63812. * An event triggered after rendering the postprocess
  63813. */
  63814. this.onAfterRenderObservable = new BABYLON.Observable();
  63815. if (camera != null) {
  63816. this._camera = camera;
  63817. this._scene = camera.getScene();
  63818. camera.attachPostProcess(this);
  63819. this._engine = this._scene.getEngine();
  63820. this._scene.postProcesses.push(this);
  63821. }
  63822. else if (engine) {
  63823. this._engine = engine;
  63824. this._engine.postProcesses.push(this);
  63825. }
  63826. this._options = options;
  63827. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63828. this._reusable = reusable || false;
  63829. this._textureType = textureType;
  63830. this._samplers = samplers || [];
  63831. this._samplers.push("textureSampler");
  63832. this._fragmentUrl = fragmentUrl;
  63833. this._vertexUrl = vertexUrl;
  63834. this._parameters = parameters || [];
  63835. this._parameters.push("scale");
  63836. this._indexParameters = indexParameters;
  63837. if (!blockCompilation) {
  63838. this.updateEffect(defines);
  63839. }
  63840. }
  63841. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63842. /**
  63843. * A function that is added to the onActivateObservable
  63844. */
  63845. set: function (callback) {
  63846. if (this._onActivateObserver) {
  63847. this.onActivateObservable.remove(this._onActivateObserver);
  63848. }
  63849. if (callback) {
  63850. this._onActivateObserver = this.onActivateObservable.add(callback);
  63851. }
  63852. },
  63853. enumerable: true,
  63854. configurable: true
  63855. });
  63856. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63857. /**
  63858. * A function that is added to the onSizeChangedObservable
  63859. */
  63860. set: function (callback) {
  63861. if (this._onSizeChangedObserver) {
  63862. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63863. }
  63864. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63865. },
  63866. enumerable: true,
  63867. configurable: true
  63868. });
  63869. Object.defineProperty(PostProcess.prototype, "onApply", {
  63870. /**
  63871. * A function that is added to the onApplyObservable
  63872. */
  63873. set: function (callback) {
  63874. if (this._onApplyObserver) {
  63875. this.onApplyObservable.remove(this._onApplyObserver);
  63876. }
  63877. this._onApplyObserver = this.onApplyObservable.add(callback);
  63878. },
  63879. enumerable: true,
  63880. configurable: true
  63881. });
  63882. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63883. /**
  63884. * A function that is added to the onBeforeRenderObservable
  63885. */
  63886. set: function (callback) {
  63887. if (this._onBeforeRenderObserver) {
  63888. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63889. }
  63890. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63891. },
  63892. enumerable: true,
  63893. configurable: true
  63894. });
  63895. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63896. /**
  63897. * A function that is added to the onAfterRenderObservable
  63898. */
  63899. set: function (callback) {
  63900. if (this._onAfterRenderObserver) {
  63901. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63902. }
  63903. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63904. },
  63905. enumerable: true,
  63906. configurable: true
  63907. });
  63908. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63909. /**
  63910. * 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
  63911. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63912. */
  63913. get: function () {
  63914. return this._textures.data[this._currentRenderTextureInd];
  63915. },
  63916. set: function (value) {
  63917. this._forcedOutputTexture = value;
  63918. },
  63919. enumerable: true,
  63920. configurable: true
  63921. });
  63922. /**
  63923. * Gets the camera which post process is applied to.
  63924. * @returns The camera the post process is applied to.
  63925. */
  63926. PostProcess.prototype.getCamera = function () {
  63927. return this._camera;
  63928. };
  63929. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63930. /**
  63931. * Gets the texel size of the postprocess.
  63932. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63933. */
  63934. get: function () {
  63935. if (this._shareOutputWithPostProcess) {
  63936. return this._shareOutputWithPostProcess.texelSize;
  63937. }
  63938. if (this._forcedOutputTexture) {
  63939. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63940. }
  63941. return this._texelSize;
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. /**
  63947. * Gets the engine which this post process belongs to.
  63948. * @returns The engine the post process was enabled with.
  63949. */
  63950. PostProcess.prototype.getEngine = function () {
  63951. return this._engine;
  63952. };
  63953. /**
  63954. * The effect that is created when initializing the post process.
  63955. * @returns The created effect corrisponding the the postprocess.
  63956. */
  63957. PostProcess.prototype.getEffect = function () {
  63958. return this._effect;
  63959. };
  63960. /**
  63961. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63962. * @param postProcess The post process to share the output with.
  63963. * @returns This post process.
  63964. */
  63965. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63966. this._disposeTextures();
  63967. this._shareOutputWithPostProcess = postProcess;
  63968. return this;
  63969. };
  63970. /**
  63971. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63972. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63973. */
  63974. PostProcess.prototype.useOwnOutput = function () {
  63975. if (this._textures.length == 0) {
  63976. this._textures = new BABYLON.SmartArray(2);
  63977. }
  63978. this._shareOutputWithPostProcess = null;
  63979. };
  63980. /**
  63981. * Updates the effect with the current post process compile time values and recompiles the shader.
  63982. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63983. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63984. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63985. * @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
  63986. * @param onCompiled Called when the shader has been compiled.
  63987. * @param onError Called if there is an error when compiling a shader.
  63988. */
  63989. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63990. if (defines === void 0) { defines = null; }
  63991. if (uniforms === void 0) { uniforms = null; }
  63992. if (samplers === void 0) { samplers = null; }
  63993. 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);
  63994. };
  63995. /**
  63996. * The post process is reusable if it can be used multiple times within one frame.
  63997. * @returns If the post process is reusable
  63998. */
  63999. PostProcess.prototype.isReusable = function () {
  64000. return this._reusable;
  64001. };
  64002. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64003. PostProcess.prototype.markTextureDirty = function () {
  64004. this.width = -1;
  64005. };
  64006. /**
  64007. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64008. * 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.
  64009. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64010. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64011. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64012. * @returns The target texture that was bound to be written to.
  64013. */
  64014. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64015. var _this = this;
  64016. if (sourceTexture === void 0) { sourceTexture = null; }
  64017. camera = camera || this._camera;
  64018. var scene = camera.getScene();
  64019. var engine = scene.getEngine();
  64020. var maxSize = engine.getCaps().maxTextureSize;
  64021. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64022. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64023. // 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
  64024. var webVRCamera = camera.parent;
  64025. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64026. requiredWidth /= 2;
  64027. }
  64028. var desiredWidth = (this._options.width || requiredWidth);
  64029. var desiredHeight = this._options.height || requiredHeight;
  64030. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64031. if (this.adaptScaleToCurrentViewport) {
  64032. var currentViewport = engine.currentViewport;
  64033. if (currentViewport) {
  64034. desiredWidth *= currentViewport.width;
  64035. desiredHeight *= currentViewport.height;
  64036. }
  64037. }
  64038. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64039. if (!this._options.width) {
  64040. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64041. }
  64042. if (!this._options.height) {
  64043. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64044. }
  64045. }
  64046. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64047. if (this._textures.length > 0) {
  64048. for (var i = 0; i < this._textures.length; i++) {
  64049. this._engine._releaseTexture(this._textures.data[i]);
  64050. }
  64051. this._textures.reset();
  64052. }
  64053. this.width = desiredWidth;
  64054. this.height = desiredHeight;
  64055. var textureSize = { width: this.width, height: this.height };
  64056. var textureOptions = {
  64057. generateMipMaps: false,
  64058. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64059. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64060. samplingMode: this.renderTargetSamplingMode,
  64061. type: this._textureType
  64062. };
  64063. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64064. if (this._reusable) {
  64065. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64066. }
  64067. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64068. this.onSizeChangedObservable.notifyObservers(this);
  64069. }
  64070. this._textures.forEach(function (texture) {
  64071. if (texture.samples !== _this.samples) {
  64072. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64073. }
  64074. });
  64075. }
  64076. var target;
  64077. if (this._shareOutputWithPostProcess) {
  64078. target = this._shareOutputWithPostProcess.inputTexture;
  64079. }
  64080. else if (this._forcedOutputTexture) {
  64081. target = this._forcedOutputTexture;
  64082. this.width = this._forcedOutputTexture.width;
  64083. this.height = this._forcedOutputTexture.height;
  64084. }
  64085. else {
  64086. target = this.inputTexture;
  64087. }
  64088. // Bind the input of this post process to be used as the output of the previous post process.
  64089. if (this.enablePixelPerfectMode) {
  64090. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64091. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64092. }
  64093. else {
  64094. this._scaleRatio.copyFromFloats(1, 1);
  64095. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64096. }
  64097. this.onActivateObservable.notifyObservers(camera);
  64098. // Clear
  64099. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64100. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64101. }
  64102. if (this._reusable) {
  64103. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64104. }
  64105. return target;
  64106. };
  64107. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64108. /**
  64109. * If the post process is supported.
  64110. */
  64111. get: function () {
  64112. return this._effect.isSupported;
  64113. },
  64114. enumerable: true,
  64115. configurable: true
  64116. });
  64117. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64118. /**
  64119. * The aspect ratio of the output texture.
  64120. */
  64121. get: function () {
  64122. if (this._shareOutputWithPostProcess) {
  64123. return this._shareOutputWithPostProcess.aspectRatio;
  64124. }
  64125. if (this._forcedOutputTexture) {
  64126. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64127. }
  64128. return this.width / this.height;
  64129. },
  64130. enumerable: true,
  64131. configurable: true
  64132. });
  64133. /**
  64134. * Get a value indicating if the post-process is ready to be used
  64135. * @returns true if the post-process is ready (shader is compiled)
  64136. */
  64137. PostProcess.prototype.isReady = function () {
  64138. return this._effect && this._effect.isReady();
  64139. };
  64140. /**
  64141. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64142. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64143. */
  64144. PostProcess.prototype.apply = function () {
  64145. // Check
  64146. if (!this._effect || !this._effect.isReady())
  64147. return null;
  64148. // States
  64149. this._engine.enableEffect(this._effect);
  64150. this._engine.setState(false);
  64151. this._engine.setDepthBuffer(false);
  64152. this._engine.setDepthWrite(false);
  64153. // Alpha
  64154. this._engine.setAlphaMode(this.alphaMode);
  64155. if (this.alphaConstants) {
  64156. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64157. }
  64158. // Bind the output texture of the preivous post process as the input to this post process.
  64159. var source;
  64160. if (this._shareOutputWithPostProcess) {
  64161. source = this._shareOutputWithPostProcess.inputTexture;
  64162. }
  64163. else if (this._forcedOutputTexture) {
  64164. source = this._forcedOutputTexture;
  64165. }
  64166. else {
  64167. source = this.inputTexture;
  64168. }
  64169. this._effect._bindTexture("textureSampler", source);
  64170. // Parameters
  64171. this._effect.setVector2("scale", this._scaleRatio);
  64172. this.onApplyObservable.notifyObservers(this._effect);
  64173. return this._effect;
  64174. };
  64175. PostProcess.prototype._disposeTextures = function () {
  64176. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64177. return;
  64178. }
  64179. if (this._textures.length > 0) {
  64180. for (var i = 0; i < this._textures.length; i++) {
  64181. this._engine._releaseTexture(this._textures.data[i]);
  64182. }
  64183. }
  64184. this._textures.dispose();
  64185. };
  64186. /**
  64187. * Disposes the post process.
  64188. * @param camera The camera to dispose the post process on.
  64189. */
  64190. PostProcess.prototype.dispose = function (camera) {
  64191. camera = camera || this._camera;
  64192. this._disposeTextures();
  64193. if (this._scene) {
  64194. var index_1 = this._scene.postProcesses.indexOf(this);
  64195. if (index_1 !== -1) {
  64196. this._scene.postProcesses.splice(index_1, 1);
  64197. }
  64198. }
  64199. else {
  64200. var index_2 = this._engine.postProcesses.indexOf(this);
  64201. if (index_2 !== -1) {
  64202. this._engine.postProcesses.splice(index_2, 1);
  64203. }
  64204. }
  64205. if (!camera) {
  64206. return;
  64207. }
  64208. camera.detachPostProcess(this);
  64209. var index = camera._postProcesses.indexOf(this);
  64210. if (index === 0 && camera._postProcesses.length > 0) {
  64211. var firstPostProcess = this._camera._getFirstPostProcess();
  64212. if (firstPostProcess) {
  64213. firstPostProcess.markTextureDirty();
  64214. }
  64215. }
  64216. this.onActivateObservable.clear();
  64217. this.onAfterRenderObservable.clear();
  64218. this.onApplyObservable.clear();
  64219. this.onBeforeRenderObservable.clear();
  64220. this.onSizeChangedObservable.clear();
  64221. };
  64222. return PostProcess;
  64223. }());
  64224. BABYLON.PostProcess = PostProcess;
  64225. })(BABYLON || (BABYLON = {}));
  64226. //# sourceMappingURL=babylon.postProcess.js.map
  64227. var BABYLON;
  64228. (function (BABYLON) {
  64229. var PassPostProcess = /** @class */ (function (_super) {
  64230. __extends(PassPostProcess, _super);
  64231. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64232. if (camera === void 0) { camera = null; }
  64233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64234. if (blockCompilation === void 0) { blockCompilation = false; }
  64235. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64236. }
  64237. return PassPostProcess;
  64238. }(BABYLON.PostProcess));
  64239. BABYLON.PassPostProcess = PassPostProcess;
  64240. })(BABYLON || (BABYLON = {}));
  64241. //# sourceMappingURL=babylon.passPostProcess.js.map
  64242. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64243. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64244. s = arguments[i];
  64245. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64246. t[p] = s[p];
  64247. }
  64248. return t;
  64249. };
  64250. var BABYLON;
  64251. (function (BABYLON) {
  64252. /**
  64253. * Default implementation IShadowGenerator.
  64254. * This is the main object responsible of generating shadows in the framework.
  64255. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64256. */
  64257. var ShadowGenerator = /** @class */ (function () {
  64258. /**
  64259. * Creates a ShadowGenerator object.
  64260. * A ShadowGenerator is the required tool to use the shadows.
  64261. * Each light casting shadows needs to use its own ShadowGenerator.
  64262. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64263. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64264. * @param light The light object generating the shadows.
  64265. * @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.
  64266. */
  64267. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64268. this._bias = 0.00005;
  64269. this._normalBias = 0;
  64270. this._blurBoxOffset = 1;
  64271. this._blurScale = 2;
  64272. this._blurKernel = 1;
  64273. this._useKernelBlur = false;
  64274. this._filter = ShadowGenerator.FILTER_NONE;
  64275. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64276. this._contactHardeningLightSizeUVRatio = 0.1;
  64277. this._darkness = 0;
  64278. this._transparencyShadow = false;
  64279. /**
  64280. * Controls the extent to which the shadows fade out at the edge of the frustum
  64281. * Used only by directionals and spots
  64282. */
  64283. this.frustumEdgeFalloff = 0;
  64284. /**
  64285. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64286. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64287. * It might on the other hand introduce peter panning.
  64288. */
  64289. this.forceBackFacesOnly = false;
  64290. this._lightDirection = BABYLON.Vector3.Zero();
  64291. this._viewMatrix = BABYLON.Matrix.Zero();
  64292. this._projectionMatrix = BABYLON.Matrix.Zero();
  64293. this._transformMatrix = BABYLON.Matrix.Zero();
  64294. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64295. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64296. this._currentFaceIndex = 0;
  64297. this._currentFaceIndexCache = 0;
  64298. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64299. this._mapSize = mapSize;
  64300. this._light = light;
  64301. this._scene = light.getScene();
  64302. light._shadowGenerator = this;
  64303. // Texture type fallback from float to int if not supported.
  64304. var caps = this._scene.getEngine().getCaps();
  64305. if (!useFullFloatFirst) {
  64306. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64307. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64308. }
  64309. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64310. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64311. }
  64312. else {
  64313. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64314. }
  64315. }
  64316. else {
  64317. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64318. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64319. }
  64320. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64321. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64322. }
  64323. else {
  64324. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64325. }
  64326. }
  64327. this._initializeGenerator();
  64328. this._applyFilterValues();
  64329. }
  64330. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64331. /**
  64332. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64333. */
  64334. get: function () {
  64335. return this._bias;
  64336. },
  64337. /**
  64338. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64339. */
  64340. set: function (bias) {
  64341. this._bias = bias;
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64347. /**
  64348. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64349. */
  64350. get: function () {
  64351. return this._normalBias;
  64352. },
  64353. /**
  64354. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64355. */
  64356. set: function (normalBias) {
  64357. this._normalBias = normalBias;
  64358. },
  64359. enumerable: true,
  64360. configurable: true
  64361. });
  64362. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64363. /**
  64364. * Gets the blur box offset: offset applied during the blur pass.
  64365. * Only usefull if useKernelBlur = false
  64366. */
  64367. get: function () {
  64368. return this._blurBoxOffset;
  64369. },
  64370. /**
  64371. * Sets the blur box offset: offset applied during the blur pass.
  64372. * Only usefull if useKernelBlur = false
  64373. */
  64374. set: function (value) {
  64375. if (this._blurBoxOffset === value) {
  64376. return;
  64377. }
  64378. this._blurBoxOffset = value;
  64379. this._disposeBlurPostProcesses();
  64380. },
  64381. enumerable: true,
  64382. configurable: true
  64383. });
  64384. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64385. /**
  64386. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64387. * 2 means half of the size.
  64388. */
  64389. get: function () {
  64390. return this._blurScale;
  64391. },
  64392. /**
  64393. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64394. * 2 means half of the size.
  64395. */
  64396. set: function (value) {
  64397. if (this._blurScale === value) {
  64398. return;
  64399. }
  64400. this._blurScale = value;
  64401. this._disposeBlurPostProcesses();
  64402. },
  64403. enumerable: true,
  64404. configurable: true
  64405. });
  64406. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64407. /**
  64408. * Gets the blur kernel: kernel size of the blur pass.
  64409. * Only usefull if useKernelBlur = true
  64410. */
  64411. get: function () {
  64412. return this._blurKernel;
  64413. },
  64414. /**
  64415. * Sets the blur kernel: kernel size of the blur pass.
  64416. * Only usefull if useKernelBlur = true
  64417. */
  64418. set: function (value) {
  64419. if (this._blurKernel === value) {
  64420. return;
  64421. }
  64422. this._blurKernel = value;
  64423. this._disposeBlurPostProcesses();
  64424. },
  64425. enumerable: true,
  64426. configurable: true
  64427. });
  64428. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64429. /**
  64430. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64431. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64432. */
  64433. get: function () {
  64434. return this._useKernelBlur;
  64435. },
  64436. /**
  64437. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64438. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64439. */
  64440. set: function (value) {
  64441. if (this._useKernelBlur === value) {
  64442. return;
  64443. }
  64444. this._useKernelBlur = value;
  64445. this._disposeBlurPostProcesses();
  64446. },
  64447. enumerable: true,
  64448. configurable: true
  64449. });
  64450. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64451. /**
  64452. * Gets the depth scale used in ESM mode.
  64453. */
  64454. get: function () {
  64455. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64456. },
  64457. /**
  64458. * Sets the depth scale used in ESM mode.
  64459. * This can override the scale stored on the light.
  64460. */
  64461. set: function (value) {
  64462. this._depthScale = value;
  64463. },
  64464. enumerable: true,
  64465. configurable: true
  64466. });
  64467. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64468. /**
  64469. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64470. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64471. */
  64472. get: function () {
  64473. return this._filter;
  64474. },
  64475. /**
  64476. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64477. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64478. */
  64479. set: function (value) {
  64480. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64481. if (this._light.needCube()) {
  64482. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64483. this.useExponentialShadowMap = true;
  64484. return;
  64485. }
  64486. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64487. this.useCloseExponentialShadowMap = true;
  64488. return;
  64489. }
  64490. // PCF on cubemap would also be expensive
  64491. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64492. this.usePoissonSampling = true;
  64493. return;
  64494. }
  64495. }
  64496. // Weblg1 fallback for PCF.
  64497. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64498. if (this._scene.getEngine().webGLVersion === 1) {
  64499. this.usePoissonSampling = true;
  64500. return;
  64501. }
  64502. }
  64503. if (this._filter === value) {
  64504. return;
  64505. }
  64506. this._filter = value;
  64507. this._disposeBlurPostProcesses();
  64508. this._applyFilterValues();
  64509. this._light._markMeshesAsLightDirty();
  64510. },
  64511. enumerable: true,
  64512. configurable: true
  64513. });
  64514. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64515. /**
  64516. * Gets if the current filter is set to Poisson Sampling.
  64517. */
  64518. get: function () {
  64519. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64520. },
  64521. /**
  64522. * Sets the current filter to Poisson Sampling.
  64523. */
  64524. set: function (value) {
  64525. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64526. return;
  64527. }
  64528. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64529. },
  64530. enumerable: true,
  64531. configurable: true
  64532. });
  64533. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64534. /**
  64535. * Gets if the current filter is set to VSM.
  64536. * DEPRECATED. Should use useExponentialShadowMap instead.
  64537. */
  64538. get: function () {
  64539. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64540. return this.useExponentialShadowMap;
  64541. },
  64542. /**
  64543. * Sets the current filter is to VSM.
  64544. * DEPRECATED. Should use useExponentialShadowMap instead.
  64545. */
  64546. set: function (value) {
  64547. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64548. this.useExponentialShadowMap = value;
  64549. },
  64550. enumerable: true,
  64551. configurable: true
  64552. });
  64553. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64554. /**
  64555. * Gets if the current filter is set to blurred VSM.
  64556. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64557. */
  64558. get: function () {
  64559. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64560. return this.useBlurExponentialShadowMap;
  64561. },
  64562. /**
  64563. * Sets the current filter is to blurred VSM.
  64564. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64565. */
  64566. set: function (value) {
  64567. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64568. this.useBlurExponentialShadowMap = value;
  64569. },
  64570. enumerable: true,
  64571. configurable: true
  64572. });
  64573. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64574. /**
  64575. * Gets if the current filter is set to ESM.
  64576. */
  64577. get: function () {
  64578. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64579. },
  64580. /**
  64581. * Sets the current filter is to ESM.
  64582. */
  64583. set: function (value) {
  64584. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64585. return;
  64586. }
  64587. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64588. },
  64589. enumerable: true,
  64590. configurable: true
  64591. });
  64592. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64593. /**
  64594. * Gets if the current filter is set to filtered ESM.
  64595. */
  64596. get: function () {
  64597. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64598. },
  64599. /**
  64600. * Gets if the current filter is set to filtered ESM.
  64601. */
  64602. set: function (value) {
  64603. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64604. return;
  64605. }
  64606. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64607. },
  64608. enumerable: true,
  64609. configurable: true
  64610. });
  64611. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64612. /**
  64613. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64614. * exponential to prevent steep falloff artifacts).
  64615. */
  64616. get: function () {
  64617. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64618. },
  64619. /**
  64620. * Sets the current filter to "close ESM" (using the inverse of the
  64621. * exponential to prevent steep falloff artifacts).
  64622. */
  64623. set: function (value) {
  64624. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64625. return;
  64626. }
  64627. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64628. },
  64629. enumerable: true,
  64630. configurable: true
  64631. });
  64632. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64633. /**
  64634. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64635. * exponential to prevent steep falloff artifacts).
  64636. */
  64637. get: function () {
  64638. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64639. },
  64640. /**
  64641. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64642. * exponential to prevent steep falloff artifacts).
  64643. */
  64644. set: function (value) {
  64645. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64646. return;
  64647. }
  64648. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64649. },
  64650. enumerable: true,
  64651. configurable: true
  64652. });
  64653. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64654. /**
  64655. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64656. */
  64657. get: function () {
  64658. return this.filter === ShadowGenerator.FILTER_PCF;
  64659. },
  64660. /**
  64661. * Sets the current filter to "PCF" (percentage closer filtering).
  64662. */
  64663. set: function (value) {
  64664. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64665. return;
  64666. }
  64667. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64668. },
  64669. enumerable: true,
  64670. configurable: true
  64671. });
  64672. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64673. /**
  64674. * Gets the PCF or PCSS Quality.
  64675. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64676. */
  64677. get: function () {
  64678. return this._filteringQuality;
  64679. },
  64680. /**
  64681. * Sets the PCF or PCSS Quality.
  64682. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64683. */
  64684. set: function (filteringQuality) {
  64685. this._filteringQuality = filteringQuality;
  64686. },
  64687. enumerable: true,
  64688. configurable: true
  64689. });
  64690. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64691. /**
  64692. * Gets if the current filter is set to "PCSS" (contact hardening).
  64693. */
  64694. get: function () {
  64695. return this.filter === ShadowGenerator.FILTER_PCSS;
  64696. },
  64697. /**
  64698. * Sets the current filter to "PCSS" (contact hardening).
  64699. */
  64700. set: function (value) {
  64701. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64702. return;
  64703. }
  64704. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64705. },
  64706. enumerable: true,
  64707. configurable: true
  64708. });
  64709. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64710. /**
  64711. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64712. * Using a ratio helps keeping shape stability independently of the map size.
  64713. *
  64714. * It does not account for the light projection as it was having too much
  64715. * instability during the light setup or during light position changes.
  64716. *
  64717. * Only valid if useContactHardeningShadow is true.
  64718. */
  64719. get: function () {
  64720. return this._contactHardeningLightSizeUVRatio;
  64721. },
  64722. /**
  64723. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64724. * Using a ratio helps keeping shape stability independently of the map size.
  64725. *
  64726. * It does not account for the light projection as it was having too much
  64727. * instability during the light setup or during light position changes.
  64728. *
  64729. * Only valid if useContactHardeningShadow is true.
  64730. */
  64731. set: function (contactHardeningLightSizeUVRatio) {
  64732. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. /**
  64738. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64739. * 0 means strongest and 1 would means no shadow.
  64740. * @returns the darkness.
  64741. */
  64742. ShadowGenerator.prototype.getDarkness = function () {
  64743. return this._darkness;
  64744. };
  64745. /**
  64746. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64747. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64748. * @returns the shadow generator allowing fluent coding.
  64749. */
  64750. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64751. if (darkness >= 1.0)
  64752. this._darkness = 1.0;
  64753. else if (darkness <= 0.0)
  64754. this._darkness = 0.0;
  64755. else
  64756. this._darkness = darkness;
  64757. return this;
  64758. };
  64759. /**
  64760. * Sets the ability to have transparent shadow (boolean).
  64761. * @param transparent True if transparent else False
  64762. * @returns the shadow generator allowing fluent coding
  64763. */
  64764. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64765. this._transparencyShadow = transparent;
  64766. return this;
  64767. };
  64768. /**
  64769. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64770. * @returns The render target texture if present otherwise, null
  64771. */
  64772. ShadowGenerator.prototype.getShadowMap = function () {
  64773. return this._shadowMap;
  64774. };
  64775. /**
  64776. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64777. * @returns The render target texture if the shadow map is present otherwise, null
  64778. */
  64779. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64780. if (this._shadowMap2) {
  64781. return this._shadowMap2;
  64782. }
  64783. return this._shadowMap;
  64784. };
  64785. /**
  64786. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64787. * @param mesh Mesh to add
  64788. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64789. * @returns the Shadow Generator itself
  64790. */
  64791. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64792. if (includeDescendants === void 0) { includeDescendants = true; }
  64793. if (!this._shadowMap) {
  64794. return this;
  64795. }
  64796. if (!this._shadowMap.renderList) {
  64797. this._shadowMap.renderList = [];
  64798. }
  64799. this._shadowMap.renderList.push(mesh);
  64800. if (includeDescendants) {
  64801. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64802. }
  64803. return this;
  64804. var _a;
  64805. };
  64806. /**
  64807. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64808. * @param mesh Mesh to remove
  64809. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64810. * @returns the Shadow Generator itself
  64811. */
  64812. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64813. if (includeDescendants === void 0) { includeDescendants = true; }
  64814. if (!this._shadowMap || !this._shadowMap.renderList) {
  64815. return this;
  64816. }
  64817. var index = this._shadowMap.renderList.indexOf(mesh);
  64818. if (index !== -1) {
  64819. this._shadowMap.renderList.splice(index, 1);
  64820. }
  64821. if (includeDescendants) {
  64822. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64823. var child = _a[_i];
  64824. this.removeShadowCaster(child);
  64825. }
  64826. }
  64827. return this;
  64828. };
  64829. /**
  64830. * Returns the associated light object.
  64831. * @returns the light generating the shadow
  64832. */
  64833. ShadowGenerator.prototype.getLight = function () {
  64834. return this._light;
  64835. };
  64836. ShadowGenerator.prototype._initializeGenerator = function () {
  64837. this._light._markMeshesAsLightDirty();
  64838. this._initializeShadowMap();
  64839. };
  64840. ShadowGenerator.prototype._initializeShadowMap = function () {
  64841. var _this = this;
  64842. // Render target
  64843. var engine = this._scene.getEngine();
  64844. if (engine.webGLVersion > 1) {
  64845. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64846. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64847. }
  64848. else {
  64849. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64850. }
  64851. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64852. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64853. this._shadowMap.anisotropicFilteringLevel = 1;
  64854. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64855. this._shadowMap.renderParticles = false;
  64856. this._shadowMap.ignoreCameraViewport = true;
  64857. // Record Face Index before render.
  64858. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64859. _this._currentFaceIndex = faceIndex;
  64860. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64861. engine.setColorWrite(false);
  64862. }
  64863. });
  64864. // Custom render function.
  64865. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64866. // Blur if required afer render.
  64867. this._shadowMap.onAfterUnbindObservable.add(function () {
  64868. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64869. engine.setColorWrite(true);
  64870. }
  64871. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64872. return;
  64873. }
  64874. var shadowMap = _this.getShadowMapForRendering();
  64875. if (shadowMap) {
  64876. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64877. }
  64878. });
  64879. // Clear according to the chosen filter.
  64880. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64881. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64882. this._shadowMap.onClearObservable.add(function (engine) {
  64883. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64884. engine.clear(clearOne, false, true, false);
  64885. }
  64886. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64887. engine.clear(clearZero, true, true, false);
  64888. }
  64889. else {
  64890. engine.clear(clearOne, true, true, false);
  64891. }
  64892. });
  64893. };
  64894. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64895. var _this = this;
  64896. var engine = this._scene.getEngine();
  64897. var targetSize = this._mapSize / this.blurScale;
  64898. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64899. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64900. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64901. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64902. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64903. }
  64904. if (this.useKernelBlur) {
  64905. 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);
  64906. this._kernelBlurXPostprocess.width = targetSize;
  64907. this._kernelBlurXPostprocess.height = targetSize;
  64908. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64909. effect.setTexture("textureSampler", _this._shadowMap);
  64910. });
  64911. 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);
  64912. this._kernelBlurXPostprocess.autoClear = false;
  64913. this._kernelBlurYPostprocess.autoClear = false;
  64914. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64915. this._kernelBlurXPostprocess.packedFloat = true;
  64916. this._kernelBlurYPostprocess.packedFloat = true;
  64917. }
  64918. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64919. }
  64920. else {
  64921. 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);
  64922. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64923. effect.setFloat2("screenSize", targetSize, targetSize);
  64924. effect.setTexture("textureSampler", _this._shadowMap);
  64925. });
  64926. this._boxBlurPostprocess.autoClear = false;
  64927. this._blurPostProcesses = [this._boxBlurPostprocess];
  64928. }
  64929. };
  64930. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64931. var index;
  64932. var engine = this._scene.getEngine();
  64933. if (depthOnlySubMeshes.length) {
  64934. engine.setColorWrite(false);
  64935. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64936. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64937. }
  64938. engine.setColorWrite(true);
  64939. }
  64940. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64941. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64942. }
  64943. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64944. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64945. }
  64946. if (this._transparencyShadow) {
  64947. for (index = 0; index < transparentSubMeshes.length; index++) {
  64948. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64949. }
  64950. }
  64951. };
  64952. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64953. var _this = this;
  64954. var mesh = subMesh.getRenderingMesh();
  64955. var scene = this._scene;
  64956. var engine = scene.getEngine();
  64957. var material = subMesh.getMaterial();
  64958. if (!material) {
  64959. return;
  64960. }
  64961. // Culling
  64962. engine.setState(material.backFaceCulling);
  64963. // Managing instances
  64964. var batch = mesh._getInstancesRenderList(subMesh._id);
  64965. if (batch.mustReturn) {
  64966. return;
  64967. }
  64968. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64969. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64970. engine.enableEffect(this._effect);
  64971. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64972. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64973. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64974. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64975. this._effect.setVector3("lightData", this._cachedDirection);
  64976. }
  64977. else {
  64978. this._effect.setVector3("lightData", this._cachedPosition);
  64979. }
  64980. if (scene.activeCamera) {
  64981. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64982. }
  64983. // Alpha test
  64984. if (material && material.needAlphaTesting()) {
  64985. var alphaTexture = material.getAlphaTestTexture();
  64986. if (alphaTexture) {
  64987. this._effect.setTexture("diffuseSampler", alphaTexture);
  64988. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64989. }
  64990. }
  64991. // Bones
  64992. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64993. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64994. }
  64995. // Morph targets
  64996. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64997. if (this.forceBackFacesOnly) {
  64998. engine.setState(true, 0, false, true);
  64999. }
  65000. // Draw
  65001. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65002. if (this.forceBackFacesOnly) {
  65003. engine.setState(true, 0, false, false);
  65004. }
  65005. }
  65006. else {
  65007. // Need to reset refresh rate of the shadowMap
  65008. if (this._shadowMap) {
  65009. this._shadowMap.resetRefreshCounter();
  65010. }
  65011. }
  65012. };
  65013. ShadowGenerator.prototype._applyFilterValues = function () {
  65014. if (!this._shadowMap) {
  65015. return;
  65016. }
  65017. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65018. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65019. }
  65020. else {
  65021. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65022. }
  65023. };
  65024. /**
  65025. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65026. * @param onCompiled Callback triggered at the and of the effects compilation
  65027. * @param options Sets of optional options forcing the compilation with different modes
  65028. */
  65029. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65030. var _this = this;
  65031. var localOptions = __assign({ useInstances: false }, options);
  65032. var shadowMap = this.getShadowMap();
  65033. if (!shadowMap) {
  65034. if (onCompiled) {
  65035. onCompiled(this);
  65036. }
  65037. return;
  65038. }
  65039. var renderList = shadowMap.renderList;
  65040. if (!renderList) {
  65041. if (onCompiled) {
  65042. onCompiled(this);
  65043. }
  65044. return;
  65045. }
  65046. var subMeshes = new Array();
  65047. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65048. var mesh = renderList_1[_i];
  65049. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65050. }
  65051. if (subMeshes.length === 0) {
  65052. if (onCompiled) {
  65053. onCompiled(this);
  65054. }
  65055. return;
  65056. }
  65057. var currentIndex = 0;
  65058. var checkReady = function () {
  65059. if (!_this._scene || !_this._scene.getEngine()) {
  65060. return;
  65061. }
  65062. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65063. currentIndex++;
  65064. if (currentIndex >= subMeshes.length) {
  65065. if (onCompiled) {
  65066. onCompiled(_this);
  65067. }
  65068. return;
  65069. }
  65070. }
  65071. setTimeout(checkReady, 16);
  65072. };
  65073. checkReady();
  65074. };
  65075. /**
  65076. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65077. * @param options Sets of optional options forcing the compilation with different modes
  65078. * @returns A promise that resolves when the compilation completes
  65079. */
  65080. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65081. var _this = this;
  65082. return new Promise(function (resolve) {
  65083. _this.forceCompilation(function () {
  65084. resolve();
  65085. }, options);
  65086. });
  65087. };
  65088. /**
  65089. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65090. * @param subMesh The submesh we want to render in the shadow map
  65091. * @param useInstances Defines wether will draw in the map using instances
  65092. * @returns true if ready otherwise, false
  65093. */
  65094. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65095. var defines = [];
  65096. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65097. defines.push("#define FLOAT");
  65098. }
  65099. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65100. defines.push("#define ESM");
  65101. }
  65102. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65103. defines.push("#define DEPTHTEXTURE");
  65104. }
  65105. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65106. var mesh = subMesh.getMesh();
  65107. var material = subMesh.getMaterial();
  65108. // Normal bias.
  65109. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65110. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65111. defines.push("#define NORMAL");
  65112. if (mesh.nonUniformScaling) {
  65113. defines.push("#define NONUNIFORMSCALING");
  65114. }
  65115. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65116. defines.push("#define DIRECTIONINLIGHTDATA");
  65117. }
  65118. }
  65119. // Alpha test
  65120. if (material && material.needAlphaTesting()) {
  65121. var alphaTexture = material.getAlphaTestTexture();
  65122. if (alphaTexture) {
  65123. defines.push("#define ALPHATEST");
  65124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65125. attribs.push(BABYLON.VertexBuffer.UVKind);
  65126. defines.push("#define UV1");
  65127. }
  65128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65129. if (alphaTexture.coordinatesIndex === 1) {
  65130. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65131. defines.push("#define UV2");
  65132. }
  65133. }
  65134. }
  65135. }
  65136. // Bones
  65137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65140. if (mesh.numBoneInfluencers > 4) {
  65141. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65142. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65143. }
  65144. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65145. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65146. }
  65147. else {
  65148. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65149. }
  65150. // Morph targets
  65151. var manager = mesh.morphTargetManager;
  65152. var morphInfluencers = 0;
  65153. if (manager) {
  65154. if (manager.numInfluencers > 0) {
  65155. defines.push("#define MORPHTARGETS");
  65156. morphInfluencers = manager.numInfluencers;
  65157. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65158. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65159. }
  65160. }
  65161. // Instances
  65162. if (useInstances) {
  65163. defines.push("#define INSTANCES");
  65164. attribs.push("world0");
  65165. attribs.push("world1");
  65166. attribs.push("world2");
  65167. attribs.push("world3");
  65168. }
  65169. // Get correct effect
  65170. var join = defines.join("\n");
  65171. if (this._cachedDefines !== join) {
  65172. this._cachedDefines = join;
  65173. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65174. }
  65175. if (!this._effect.isReady()) {
  65176. return false;
  65177. }
  65178. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65179. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65180. this._initializeBlurRTTAndPostProcesses();
  65181. }
  65182. }
  65183. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65184. return false;
  65185. }
  65186. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65187. return false;
  65188. }
  65189. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65190. return false;
  65191. }
  65192. return true;
  65193. };
  65194. /**
  65195. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65196. * @param defines Defines of the material we want to update
  65197. * @param lightIndex Index of the light in the enabled light list of the material
  65198. */
  65199. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65200. var scene = this._scene;
  65201. var light = this._light;
  65202. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65203. return;
  65204. }
  65205. defines["SHADOW" + lightIndex] = true;
  65206. if (this.useContactHardeningShadow) {
  65207. defines["SHADOWPCSS" + lightIndex] = true;
  65208. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65209. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65210. }
  65211. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65212. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65213. }
  65214. // else default to high.
  65215. }
  65216. if (this.usePercentageCloserFiltering) {
  65217. defines["SHADOWPCF" + lightIndex] = true;
  65218. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65219. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65220. }
  65221. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65222. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65223. }
  65224. // else default to high.
  65225. }
  65226. else if (this.usePoissonSampling) {
  65227. defines["SHADOWPOISSON" + lightIndex] = true;
  65228. }
  65229. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65230. defines["SHADOWESM" + lightIndex] = true;
  65231. }
  65232. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65233. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65234. }
  65235. if (light.needCube()) {
  65236. defines["SHADOWCUBE" + lightIndex] = true;
  65237. }
  65238. };
  65239. /**
  65240. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65241. * defined in the generator but impacting the effect).
  65242. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65243. * @param effect The effect we are binfing the information for
  65244. */
  65245. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65246. var light = this._light;
  65247. var scene = this._scene;
  65248. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65249. return;
  65250. }
  65251. var camera = scene.activeCamera;
  65252. if (!camera) {
  65253. return;
  65254. }
  65255. var shadowMap = this.getShadowMap();
  65256. if (!shadowMap) {
  65257. return;
  65258. }
  65259. if (!light.needCube()) {
  65260. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65261. }
  65262. // Only PCF uses depth stencil texture.
  65263. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65264. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65265. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65266. }
  65267. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65268. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65269. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65270. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65271. }
  65272. else {
  65273. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65274. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65275. }
  65276. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65277. };
  65278. /**
  65279. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65280. * (eq to shadow prjection matrix * light transform matrix)
  65281. * @returns The transform matrix used to create the shadow map
  65282. */
  65283. ShadowGenerator.prototype.getTransformMatrix = function () {
  65284. var scene = this._scene;
  65285. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65286. return this._transformMatrix;
  65287. }
  65288. this._currentRenderID = scene.getRenderId();
  65289. this._currentFaceIndexCache = this._currentFaceIndex;
  65290. var lightPosition = this._light.position;
  65291. if (this._light.computeTransformedInformation()) {
  65292. lightPosition = this._light.transformedPosition;
  65293. }
  65294. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65295. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65296. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65297. }
  65298. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65299. this._cachedPosition.copyFrom(lightPosition);
  65300. this._cachedDirection.copyFrom(this._lightDirection);
  65301. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65302. var shadowMap = this.getShadowMap();
  65303. if (shadowMap) {
  65304. var renderList = shadowMap.renderList;
  65305. if (renderList) {
  65306. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65307. }
  65308. }
  65309. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65310. }
  65311. return this._transformMatrix;
  65312. };
  65313. /**
  65314. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65315. * Cube and 2D textures for instance.
  65316. */
  65317. ShadowGenerator.prototype.recreateShadowMap = function () {
  65318. var shadowMap = this._shadowMap;
  65319. if (!shadowMap) {
  65320. return;
  65321. }
  65322. // Track render list.
  65323. var renderList = shadowMap.renderList;
  65324. // Clean up existing data.
  65325. this._disposeRTTandPostProcesses();
  65326. // Reinitializes.
  65327. this._initializeGenerator();
  65328. // Reaffect the filter to ensure a correct fallback if necessary.
  65329. this.filter = this.filter;
  65330. // Reaffect the filter.
  65331. this._applyFilterValues();
  65332. // Reaffect Render List.
  65333. this._shadowMap.renderList = renderList;
  65334. };
  65335. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65336. if (this._shadowMap2) {
  65337. this._shadowMap2.dispose();
  65338. this._shadowMap2 = null;
  65339. }
  65340. if (this._boxBlurPostprocess) {
  65341. this._boxBlurPostprocess.dispose();
  65342. this._boxBlurPostprocess = null;
  65343. }
  65344. if (this._kernelBlurXPostprocess) {
  65345. this._kernelBlurXPostprocess.dispose();
  65346. this._kernelBlurXPostprocess = null;
  65347. }
  65348. if (this._kernelBlurYPostprocess) {
  65349. this._kernelBlurYPostprocess.dispose();
  65350. this._kernelBlurYPostprocess = null;
  65351. }
  65352. this._blurPostProcesses = [];
  65353. };
  65354. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65355. if (this._shadowMap) {
  65356. this._shadowMap.dispose();
  65357. this._shadowMap = null;
  65358. }
  65359. this._disposeBlurPostProcesses();
  65360. };
  65361. /**
  65362. * Disposes the ShadowGenerator.
  65363. * Returns nothing.
  65364. */
  65365. ShadowGenerator.prototype.dispose = function () {
  65366. this._disposeRTTandPostProcesses();
  65367. if (this._light) {
  65368. this._light._shadowGenerator = null;
  65369. this._light._markMeshesAsLightDirty();
  65370. }
  65371. };
  65372. /**
  65373. * Serializes the shadow generator setup to a json object.
  65374. * @returns The serialized JSON object
  65375. */
  65376. ShadowGenerator.prototype.serialize = function () {
  65377. var serializationObject = {};
  65378. var shadowMap = this.getShadowMap();
  65379. if (!shadowMap) {
  65380. return serializationObject;
  65381. }
  65382. serializationObject.lightId = this._light.id;
  65383. serializationObject.mapSize = shadowMap.getRenderSize();
  65384. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65385. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65386. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65387. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65388. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65389. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65390. serializationObject.depthScale = this.depthScale;
  65391. serializationObject.darkness = this.getDarkness();
  65392. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65393. serializationObject.blurKernel = this.blurKernel;
  65394. serializationObject.blurScale = this.blurScale;
  65395. serializationObject.useKernelBlur = this.useKernelBlur;
  65396. serializationObject.transparencyShadow = this._transparencyShadow;
  65397. serializationObject.bias = this.bias;
  65398. serializationObject.normalBias = this.normalBias;
  65399. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65400. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65401. serializationObject.filteringQuality = this.filteringQuality;
  65402. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65403. serializationObject.renderList = [];
  65404. if (shadowMap.renderList) {
  65405. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65406. var mesh = shadowMap.renderList[meshIndex];
  65407. serializationObject.renderList.push(mesh.id);
  65408. }
  65409. }
  65410. return serializationObject;
  65411. };
  65412. /**
  65413. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65414. * @param parsedShadowGenerator The JSON object to parse
  65415. * @param scene The scene to create the shadow map for
  65416. * @returns The parsed shadow generator
  65417. */
  65418. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65419. //casting to point light, as light is missing the position attr and typescript complains.
  65420. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65421. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65422. var shadowMap = shadowGenerator.getShadowMap();
  65423. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65424. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65425. meshes.forEach(function (mesh) {
  65426. if (!shadowMap) {
  65427. return;
  65428. }
  65429. if (!shadowMap.renderList) {
  65430. shadowMap.renderList = [];
  65431. }
  65432. shadowMap.renderList.push(mesh);
  65433. });
  65434. }
  65435. if (parsedShadowGenerator.usePoissonSampling) {
  65436. shadowGenerator.usePoissonSampling = true;
  65437. }
  65438. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65439. shadowGenerator.useExponentialShadowMap = true;
  65440. }
  65441. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65442. shadowGenerator.useBlurExponentialShadowMap = true;
  65443. }
  65444. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65445. shadowGenerator.useCloseExponentialShadowMap = true;
  65446. }
  65447. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65448. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65449. }
  65450. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65451. shadowGenerator.usePercentageCloserFiltering = true;
  65452. }
  65453. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65454. shadowGenerator.useContactHardeningShadow = true;
  65455. }
  65456. if (parsedShadowGenerator.filteringQuality) {
  65457. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65458. }
  65459. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65460. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65461. }
  65462. // Backward compat
  65463. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65464. shadowGenerator.useExponentialShadowMap = true;
  65465. }
  65466. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65467. shadowGenerator.useBlurExponentialShadowMap = true;
  65468. }
  65469. if (parsedShadowGenerator.depthScale) {
  65470. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65471. }
  65472. if (parsedShadowGenerator.blurScale) {
  65473. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65474. }
  65475. if (parsedShadowGenerator.blurBoxOffset) {
  65476. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65477. }
  65478. if (parsedShadowGenerator.useKernelBlur) {
  65479. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65480. }
  65481. if (parsedShadowGenerator.blurKernel) {
  65482. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65483. }
  65484. if (parsedShadowGenerator.bias !== undefined) {
  65485. shadowGenerator.bias = parsedShadowGenerator.bias;
  65486. }
  65487. if (parsedShadowGenerator.normalBias !== undefined) {
  65488. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65489. }
  65490. if (parsedShadowGenerator.darkness) {
  65491. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65492. }
  65493. if (parsedShadowGenerator.transparencyShadow) {
  65494. shadowGenerator.setTransparencyShadow(true);
  65495. }
  65496. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65497. return shadowGenerator;
  65498. };
  65499. /**
  65500. * Shadow generator mode None: no filtering applied.
  65501. */
  65502. ShadowGenerator.FILTER_NONE = 0;
  65503. /**
  65504. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65505. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65506. */
  65507. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65508. /**
  65509. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65510. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65511. */
  65512. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65513. /**
  65514. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65515. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65516. */
  65517. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65518. /**
  65519. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65520. * edge artifacts on steep falloff.
  65521. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65522. */
  65523. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65524. /**
  65525. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65526. * edge artifacts on steep falloff.
  65527. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65528. */
  65529. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65530. /**
  65531. * Shadow generator mode PCF: Percentage Closer Filtering
  65532. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65533. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65534. */
  65535. ShadowGenerator.FILTER_PCF = 6;
  65536. /**
  65537. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65538. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65539. * Contact Hardening
  65540. */
  65541. ShadowGenerator.FILTER_PCSS = 7;
  65542. /**
  65543. * Reserved for PCF and PCSS
  65544. * Highest Quality.
  65545. *
  65546. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65547. *
  65548. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65549. */
  65550. ShadowGenerator.QUALITY_HIGH = 0;
  65551. /**
  65552. * Reserved for PCF and PCSS
  65553. * Good tradeoff for quality/perf cross devices
  65554. *
  65555. * Execute PCF on a 3*3 kernel.
  65556. *
  65557. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65558. */
  65559. ShadowGenerator.QUALITY_MEDIUM = 1;
  65560. /**
  65561. * Reserved for PCF and PCSS
  65562. * The lowest quality but the fastest.
  65563. *
  65564. * Execute PCF on a 1*1 kernel.
  65565. *
  65566. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65567. */
  65568. ShadowGenerator.QUALITY_LOW = 2;
  65569. return ShadowGenerator;
  65570. }());
  65571. BABYLON.ShadowGenerator = ShadowGenerator;
  65572. })(BABYLON || (BABYLON = {}));
  65573. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65574. var BABYLON;
  65575. (function (BABYLON) {
  65576. var DefaultLoadingScreen = /** @class */ (function () {
  65577. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65578. if (_loadingText === void 0) { _loadingText = ""; }
  65579. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65580. var _this = this;
  65581. this._renderingCanvas = _renderingCanvas;
  65582. this._loadingText = _loadingText;
  65583. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65584. // Resize
  65585. this._resizeLoadingUI = function () {
  65586. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65587. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65588. if (!_this._loadingDiv) {
  65589. return;
  65590. }
  65591. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65592. _this._loadingDiv.style.left = canvasRect.left + "px";
  65593. _this._loadingDiv.style.top = canvasRect.top + "px";
  65594. _this._loadingDiv.style.width = canvasRect.width + "px";
  65595. _this._loadingDiv.style.height = canvasRect.height + "px";
  65596. };
  65597. }
  65598. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65599. if (this._loadingDiv) {
  65600. // Do not add a loading screen if there is already one
  65601. return;
  65602. }
  65603. this._loadingDiv = document.createElement("div");
  65604. this._loadingDiv.id = "babylonjsLoadingDiv";
  65605. this._loadingDiv.style.opacity = "0";
  65606. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65607. this._loadingDiv.style.pointerEvents = "none";
  65608. // Loading text
  65609. this._loadingTextDiv = document.createElement("div");
  65610. this._loadingTextDiv.style.position = "absolute";
  65611. this._loadingTextDiv.style.left = "0";
  65612. this._loadingTextDiv.style.top = "50%";
  65613. this._loadingTextDiv.style.marginTop = "80px";
  65614. this._loadingTextDiv.style.width = "100%";
  65615. this._loadingTextDiv.style.height = "20px";
  65616. this._loadingTextDiv.style.fontFamily = "Arial";
  65617. this._loadingTextDiv.style.fontSize = "14px";
  65618. this._loadingTextDiv.style.color = "white";
  65619. this._loadingTextDiv.style.textAlign = "center";
  65620. this._loadingTextDiv.innerHTML = "Loading";
  65621. this._loadingDiv.appendChild(this._loadingTextDiv);
  65622. //set the predefined text
  65623. this._loadingTextDiv.innerHTML = this._loadingText;
  65624. // Generating keyframes
  65625. var style = document.createElement('style');
  65626. style.type = 'text/css';
  65627. 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 }";
  65628. style.innerHTML = keyFrames;
  65629. document.getElementsByTagName('head')[0].appendChild(style);
  65630. // Loading img
  65631. var imgBack = new Image();
  65632. 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";
  65633. imgBack.style.position = "absolute";
  65634. imgBack.style.left = "50%";
  65635. imgBack.style.top = "50%";
  65636. imgBack.style.marginLeft = "-60px";
  65637. imgBack.style.marginTop = "-60px";
  65638. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65639. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65640. imgBack.style.transformOrigin = "50% 50%";
  65641. imgBack.style.webkitTransformOrigin = "50% 50%";
  65642. this._loadingDiv.appendChild(imgBack);
  65643. this._resizeLoadingUI();
  65644. window.addEventListener("resize", this._resizeLoadingUI);
  65645. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65646. document.body.appendChild(this._loadingDiv);
  65647. this._loadingDiv.style.opacity = "1";
  65648. };
  65649. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65650. var _this = this;
  65651. if (!this._loadingDiv) {
  65652. return;
  65653. }
  65654. var onTransitionEnd = function () {
  65655. if (!_this._loadingDiv) {
  65656. return;
  65657. }
  65658. document.body.removeChild(_this._loadingDiv);
  65659. window.removeEventListener("resize", _this._resizeLoadingUI);
  65660. _this._loadingDiv = null;
  65661. };
  65662. this._loadingDiv.style.opacity = "0";
  65663. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65664. };
  65665. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65666. set: function (text) {
  65667. this._loadingText = text;
  65668. if (this._loadingTextDiv) {
  65669. this._loadingTextDiv.innerHTML = this._loadingText;
  65670. }
  65671. },
  65672. enumerable: true,
  65673. configurable: true
  65674. });
  65675. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65676. get: function () {
  65677. return this._loadingDivBackgroundColor;
  65678. },
  65679. set: function (color) {
  65680. this._loadingDivBackgroundColor = color;
  65681. if (!this._loadingDiv) {
  65682. return;
  65683. }
  65684. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65685. },
  65686. enumerable: true,
  65687. configurable: true
  65688. });
  65689. return DefaultLoadingScreen;
  65690. }());
  65691. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65692. })(BABYLON || (BABYLON = {}));
  65693. //# sourceMappingURL=babylon.loadingScreen.js.map
  65694. var BABYLON;
  65695. (function (BABYLON) {
  65696. var SceneLoaderProgressEvent = /** @class */ (function () {
  65697. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65698. this.lengthComputable = lengthComputable;
  65699. this.loaded = loaded;
  65700. this.total = total;
  65701. }
  65702. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65703. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65704. };
  65705. return SceneLoaderProgressEvent;
  65706. }());
  65707. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65708. var SceneLoader = /** @class */ (function () {
  65709. function SceneLoader() {
  65710. }
  65711. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65712. get: function () {
  65713. return 0;
  65714. },
  65715. enumerable: true,
  65716. configurable: true
  65717. });
  65718. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65719. get: function () {
  65720. return 1;
  65721. },
  65722. enumerable: true,
  65723. configurable: true
  65724. });
  65725. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65726. get: function () {
  65727. return 2;
  65728. },
  65729. enumerable: true,
  65730. configurable: true
  65731. });
  65732. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65733. get: function () {
  65734. return 3;
  65735. },
  65736. enumerable: true,
  65737. configurable: true
  65738. });
  65739. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65740. get: function () {
  65741. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65742. },
  65743. set: function (value) {
  65744. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65745. },
  65746. enumerable: true,
  65747. configurable: true
  65748. });
  65749. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65750. get: function () {
  65751. return SceneLoader._ShowLoadingScreen;
  65752. },
  65753. set: function (value) {
  65754. SceneLoader._ShowLoadingScreen = value;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. Object.defineProperty(SceneLoader, "loggingLevel", {
  65760. get: function () {
  65761. return SceneLoader._loggingLevel;
  65762. },
  65763. set: function (value) {
  65764. SceneLoader._loggingLevel = value;
  65765. },
  65766. enumerable: true,
  65767. configurable: true
  65768. });
  65769. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65770. get: function () {
  65771. return SceneLoader._CleanBoneMatrixWeights;
  65772. },
  65773. set: function (value) {
  65774. SceneLoader._CleanBoneMatrixWeights = value;
  65775. },
  65776. enumerable: true,
  65777. configurable: true
  65778. });
  65779. SceneLoader._getDefaultPlugin = function () {
  65780. return SceneLoader._registeredPlugins[".babylon"];
  65781. };
  65782. SceneLoader._getPluginForExtension = function (extension) {
  65783. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65784. if (registeredPlugin) {
  65785. return registeredPlugin;
  65786. }
  65787. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65788. return SceneLoader._getDefaultPlugin();
  65789. };
  65790. SceneLoader._getPluginForDirectLoad = function (data) {
  65791. for (var extension in SceneLoader._registeredPlugins) {
  65792. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65793. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65794. return SceneLoader._registeredPlugins[extension];
  65795. }
  65796. }
  65797. return SceneLoader._getDefaultPlugin();
  65798. };
  65799. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65800. if (sceneFilename.name) {
  65801. sceneFilename = sceneFilename.name;
  65802. }
  65803. var queryStringPosition = sceneFilename.indexOf("?");
  65804. if (queryStringPosition !== -1) {
  65805. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65806. }
  65807. var dotPosition = sceneFilename.lastIndexOf(".");
  65808. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65809. return SceneLoader._getPluginForExtension(extension);
  65810. };
  65811. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65812. SceneLoader._getDirectLoad = function (sceneFilename) {
  65813. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65814. return sceneFilename.substr(5);
  65815. }
  65816. return null;
  65817. };
  65818. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65819. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65820. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65821. var plugin;
  65822. if (registeredPlugin.plugin.createPlugin) {
  65823. plugin = registeredPlugin.plugin.createPlugin();
  65824. }
  65825. else {
  65826. plugin = registeredPlugin.plugin;
  65827. }
  65828. var useArrayBuffer = registeredPlugin.isBinary;
  65829. var database;
  65830. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65831. var dataCallback = function (data, responseURL) {
  65832. if (scene.isDisposed) {
  65833. onError("Scene has been disposed");
  65834. return;
  65835. }
  65836. scene.database = database;
  65837. onSuccess(plugin, data, responseURL);
  65838. };
  65839. var request = null;
  65840. var pluginDisposed = false;
  65841. var onDisposeObservable = plugin.onDisposeObservable;
  65842. if (onDisposeObservable) {
  65843. onDisposeObservable.add(function () {
  65844. pluginDisposed = true;
  65845. if (request) {
  65846. request.abort();
  65847. request = null;
  65848. }
  65849. onDispose();
  65850. });
  65851. }
  65852. var manifestChecked = function () {
  65853. if (pluginDisposed) {
  65854. return;
  65855. }
  65856. var url = rootUrl + sceneFilename;
  65857. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65858. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65859. } : undefined, database, useArrayBuffer, function (request, exception) {
  65860. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65861. });
  65862. };
  65863. if (directLoad) {
  65864. dataCallback(directLoad);
  65865. return plugin;
  65866. }
  65867. if (rootUrl.indexOf("file:") === -1) {
  65868. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65869. if (canUseOfflineSupport) {
  65870. // Also check for exceptions
  65871. var exceptionFound = false;
  65872. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65873. var regex = _a[_i];
  65874. if (regex.test(rootUrl + sceneFilename)) {
  65875. exceptionFound = true;
  65876. break;
  65877. }
  65878. }
  65879. canUseOfflineSupport = !exceptionFound;
  65880. }
  65881. if (canUseOfflineSupport) {
  65882. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65883. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65884. }
  65885. else {
  65886. manifestChecked();
  65887. }
  65888. }
  65889. // Loading file from disk via input file or drag'n'drop
  65890. else {
  65891. var fileOrString = sceneFilename;
  65892. if (fileOrString.name) { // File
  65893. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65894. }
  65895. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65896. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65897. }
  65898. else {
  65899. onError("Unable to find file named " + sceneFilename);
  65900. }
  65901. }
  65902. return plugin;
  65903. };
  65904. // Public functions
  65905. SceneLoader.GetPluginForExtension = function (extension) {
  65906. return SceneLoader._getPluginForExtension(extension).plugin;
  65907. };
  65908. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65909. return !!SceneLoader._registeredPlugins[extension];
  65910. };
  65911. SceneLoader.RegisterPlugin = function (plugin) {
  65912. if (typeof plugin.extensions === "string") {
  65913. var extension = plugin.extensions;
  65914. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65915. plugin: plugin,
  65916. isBinary: false
  65917. };
  65918. }
  65919. else {
  65920. var extensions = plugin.extensions;
  65921. Object.keys(extensions).forEach(function (extension) {
  65922. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65923. plugin: plugin,
  65924. isBinary: extensions[extension].isBinary
  65925. };
  65926. });
  65927. }
  65928. };
  65929. /**
  65930. * Import meshes into a scene
  65931. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65932. * @param rootUrl a string that defines the root url for scene and resources
  65933. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65934. * @param scene the instance of BABYLON.Scene to append to
  65935. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65936. * @param onProgress a callback with a progress event for each file being loaded
  65937. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65938. * @param pluginExtension the extension used to determine the plugin
  65939. * @returns The loaded plugin
  65940. */
  65941. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65942. if (onSuccess === void 0) { onSuccess = null; }
  65943. if (onProgress === void 0) { onProgress = null; }
  65944. if (onError === void 0) { onError = null; }
  65945. if (pluginExtension === void 0) { pluginExtension = null; }
  65946. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65947. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65948. return null;
  65949. }
  65950. var loadingToken = {};
  65951. scene._addPendingData(loadingToken);
  65952. var disposeHandler = function () {
  65953. scene._removePendingData(loadingToken);
  65954. };
  65955. var errorHandler = function (message, exception) {
  65956. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65957. if (onError) {
  65958. onError(scene, errorMessage, exception);
  65959. }
  65960. else {
  65961. BABYLON.Tools.Error(errorMessage);
  65962. // should the exception be thrown?
  65963. }
  65964. disposeHandler();
  65965. };
  65966. var progressHandler = onProgress ? function (event) {
  65967. try {
  65968. onProgress(event);
  65969. }
  65970. catch (e) {
  65971. errorHandler("Error in onProgress callback", e);
  65972. }
  65973. } : undefined;
  65974. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65975. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65976. if (onSuccess) {
  65977. try {
  65978. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65979. }
  65980. catch (e) {
  65981. errorHandler("Error in onSuccess callback", e);
  65982. }
  65983. }
  65984. scene._removePendingData(loadingToken);
  65985. };
  65986. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65987. if (plugin.rewriteRootURL) {
  65988. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65989. }
  65990. if (sceneFilename === "") {
  65991. if (sceneFilename === "") {
  65992. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65993. }
  65994. }
  65995. if (plugin.importMesh) {
  65996. var syncedPlugin = plugin;
  65997. var meshes = new Array();
  65998. var particleSystems = new Array();
  65999. var skeletons = new Array();
  66000. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66001. return;
  66002. }
  66003. scene.loadingPluginName = plugin.name;
  66004. successHandler(meshes, particleSystems, skeletons, []);
  66005. }
  66006. else {
  66007. var asyncedPlugin = plugin;
  66008. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66009. scene.loadingPluginName = plugin.name;
  66010. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66011. }).catch(function (error) {
  66012. errorHandler(error.message, error);
  66013. });
  66014. }
  66015. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66016. };
  66017. /**
  66018. * Import meshes into a scene
  66019. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66020. * @param rootUrl a string that defines the root url for scene and resources
  66021. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66022. * @param scene the instance of BABYLON.Scene to append to
  66023. * @param onProgress a callback with a progress event for each file being loaded
  66024. * @param pluginExtension the extension used to determine the plugin
  66025. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66026. */
  66027. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66028. if (onProgress === void 0) { onProgress = null; }
  66029. if (pluginExtension === void 0) { pluginExtension = null; }
  66030. return new Promise(function (resolve, reject) {
  66031. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66032. resolve({
  66033. meshes: meshes,
  66034. particleSystems: particleSystems,
  66035. skeletons: skeletons,
  66036. animationGroups: animationGroups
  66037. });
  66038. }, onProgress, function (scene, message, exception) {
  66039. reject(exception || new Error(message));
  66040. });
  66041. });
  66042. };
  66043. /**
  66044. * Load a scene
  66045. * @param rootUrl a string that defines the root url for scene and resources
  66046. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66047. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66048. * @param onSuccess a callback with the scene when import succeeds
  66049. * @param onProgress a callback with a progress event for each file being loaded
  66050. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66051. * @param pluginExtension the extension used to determine the plugin
  66052. * @returns The loaded plugin
  66053. */
  66054. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66055. if (onSuccess === void 0) { onSuccess = null; }
  66056. if (onProgress === void 0) { onProgress = null; }
  66057. if (onError === void 0) { onError = null; }
  66058. if (pluginExtension === void 0) { pluginExtension = null; }
  66059. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66060. };
  66061. /**
  66062. * Load a scene
  66063. * @param rootUrl a string that defines the root url for scene and resources
  66064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66066. * @param onProgress a callback with a progress event for each file being loaded
  66067. * @param pluginExtension the extension used to determine the plugin
  66068. * @returns The loaded scene
  66069. */
  66070. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66071. if (onProgress === void 0) { onProgress = null; }
  66072. if (pluginExtension === void 0) { pluginExtension = null; }
  66073. return new Promise(function (resolve, reject) {
  66074. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66075. resolve(scene);
  66076. }, onProgress, function (scene, message, exception) {
  66077. reject(exception || new Error(message));
  66078. }, pluginExtension);
  66079. });
  66080. };
  66081. /**
  66082. * Append a scene
  66083. * @param rootUrl a string that defines the root url for scene and resources
  66084. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66085. * @param scene is the instance of BABYLON.Scene to append to
  66086. * @param onSuccess a callback with the scene when import succeeds
  66087. * @param onProgress a callback with a progress event for each file being loaded
  66088. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66089. * @param pluginExtension the extension used to determine the plugin
  66090. * @returns The loaded plugin
  66091. */
  66092. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66093. if (onSuccess === void 0) { onSuccess = null; }
  66094. if (onProgress === void 0) { onProgress = null; }
  66095. if (onError === void 0) { onError = null; }
  66096. if (pluginExtension === void 0) { pluginExtension = null; }
  66097. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66098. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66099. return null;
  66100. }
  66101. if (SceneLoader.ShowLoadingScreen) {
  66102. scene.getEngine().displayLoadingUI();
  66103. }
  66104. var loadingToken = {};
  66105. scene._addPendingData(loadingToken);
  66106. var disposeHandler = function () {
  66107. scene._removePendingData(loadingToken);
  66108. scene.getEngine().hideLoadingUI();
  66109. };
  66110. var errorHandler = function (message, exception) {
  66111. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66112. if (onError) {
  66113. onError(scene, errorMessage, exception);
  66114. }
  66115. else {
  66116. BABYLON.Tools.Error(errorMessage);
  66117. // should the exception be thrown?
  66118. }
  66119. disposeHandler();
  66120. };
  66121. var progressHandler = onProgress ? function (event) {
  66122. try {
  66123. onProgress(event);
  66124. }
  66125. catch (e) {
  66126. errorHandler("Error in onProgress callback", e);
  66127. }
  66128. } : undefined;
  66129. var successHandler = function () {
  66130. if (onSuccess) {
  66131. try {
  66132. onSuccess(scene);
  66133. }
  66134. catch (e) {
  66135. errorHandler("Error in onSuccess callback", e);
  66136. }
  66137. }
  66138. scene._removePendingData(loadingToken);
  66139. };
  66140. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66141. if (sceneFilename === "") {
  66142. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66143. }
  66144. if (plugin.load) {
  66145. var syncedPlugin = plugin;
  66146. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66147. return;
  66148. }
  66149. scene.loadingPluginName = plugin.name;
  66150. successHandler();
  66151. }
  66152. else {
  66153. var asyncedPlugin = plugin;
  66154. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66155. scene.loadingPluginName = plugin.name;
  66156. successHandler();
  66157. }).catch(function (error) {
  66158. errorHandler(error.message, error);
  66159. });
  66160. }
  66161. if (SceneLoader.ShowLoadingScreen) {
  66162. scene.executeWhenReady(function () {
  66163. scene.getEngine().hideLoadingUI();
  66164. });
  66165. }
  66166. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66167. };
  66168. /**
  66169. * Append a scene
  66170. * @param rootUrl a string that defines the root url for scene and resources
  66171. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66172. * @param scene is the instance of BABYLON.Scene to append to
  66173. * @param onProgress a callback with a progress event for each file being loaded
  66174. * @param pluginExtension the extension used to determine the plugin
  66175. * @returns The given scene
  66176. */
  66177. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66178. if (onProgress === void 0) { onProgress = null; }
  66179. if (pluginExtension === void 0) { pluginExtension = null; }
  66180. return new Promise(function (resolve, reject) {
  66181. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66182. resolve(scene);
  66183. }, onProgress, function (scene, message, exception) {
  66184. reject(exception || new Error(message));
  66185. }, pluginExtension);
  66186. });
  66187. };
  66188. /**
  66189. * Load a scene into an asset container
  66190. * @param rootUrl a string that defines the root url for scene and resources
  66191. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66192. * @param scene is the instance of BABYLON.Scene to append to
  66193. * @param onSuccess a callback with the scene when import succeeds
  66194. * @param onProgress a callback with a progress event for each file being loaded
  66195. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66196. * @param pluginExtension the extension used to determine the plugin
  66197. * @returns The loaded plugin
  66198. */
  66199. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66200. if (onSuccess === void 0) { onSuccess = null; }
  66201. if (onProgress === void 0) { onProgress = null; }
  66202. if (onError === void 0) { onError = null; }
  66203. if (pluginExtension === void 0) { pluginExtension = null; }
  66204. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66205. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66206. return null;
  66207. }
  66208. var loadingToken = {};
  66209. scene._addPendingData(loadingToken);
  66210. var disposeHandler = function () {
  66211. scene._removePendingData(loadingToken);
  66212. };
  66213. var errorHandler = function (message, exception) {
  66214. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66215. if (onError) {
  66216. onError(scene, errorMessage, exception);
  66217. }
  66218. else {
  66219. BABYLON.Tools.Error(errorMessage);
  66220. // should the exception be thrown?
  66221. }
  66222. disposeHandler();
  66223. };
  66224. var progressHandler = onProgress ? function (event) {
  66225. try {
  66226. onProgress(event);
  66227. }
  66228. catch (e) {
  66229. errorHandler("Error in onProgress callback", e);
  66230. }
  66231. } : undefined;
  66232. var successHandler = function (assets) {
  66233. if (onSuccess) {
  66234. try {
  66235. onSuccess(assets);
  66236. }
  66237. catch (e) {
  66238. errorHandler("Error in onSuccess callback", e);
  66239. }
  66240. }
  66241. scene._removePendingData(loadingToken);
  66242. };
  66243. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66244. if (plugin.loadAssetContainer) {
  66245. var syncedPlugin = plugin;
  66246. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66247. if (!assetContainer) {
  66248. return;
  66249. }
  66250. scene.loadingPluginName = plugin.name;
  66251. successHandler(assetContainer);
  66252. }
  66253. else if (plugin.loadAssetContainerAsync) {
  66254. var asyncedPlugin = plugin;
  66255. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66256. scene.loadingPluginName = plugin.name;
  66257. successHandler(assetContainer);
  66258. }).catch(function (error) {
  66259. errorHandler(error.message, error);
  66260. });
  66261. }
  66262. else {
  66263. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66264. }
  66265. if (SceneLoader.ShowLoadingScreen) {
  66266. scene.executeWhenReady(function () {
  66267. scene.getEngine().hideLoadingUI();
  66268. });
  66269. }
  66270. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66271. };
  66272. /**
  66273. * Load a scene into an asset container
  66274. * @param rootUrl a string that defines the root url for scene and resources
  66275. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66276. * @param scene is the instance of BABYLON.Scene to append to
  66277. * @param onProgress a callback with a progress event for each file being loaded
  66278. * @param pluginExtension the extension used to determine the plugin
  66279. * @returns The loaded asset container
  66280. */
  66281. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66282. if (onProgress === void 0) { onProgress = null; }
  66283. if (pluginExtension === void 0) { pluginExtension = null; }
  66284. return new Promise(function (resolve, reject) {
  66285. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66286. resolve(assetContainer);
  66287. }, onProgress, function (scene, message, exception) {
  66288. reject(exception || new Error(message));
  66289. }, pluginExtension);
  66290. });
  66291. };
  66292. // Flags
  66293. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66294. SceneLoader._ShowLoadingScreen = true;
  66295. SceneLoader._CleanBoneMatrixWeights = false;
  66296. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66297. // Members
  66298. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66299. SceneLoader._registeredPlugins = {};
  66300. return SceneLoader;
  66301. }());
  66302. BABYLON.SceneLoader = SceneLoader;
  66303. ;
  66304. })(BABYLON || (BABYLON = {}));
  66305. //# sourceMappingURL=babylon.sceneLoader.js.map
  66306. var BABYLON;
  66307. (function (BABYLON) {
  66308. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66309. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66310. var parsedMaterial = parsedData.materials[index];
  66311. if (parsedMaterial.id === id) {
  66312. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66313. }
  66314. }
  66315. return null;
  66316. };
  66317. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66318. for (var i in names) {
  66319. if (mesh.name === names[i]) {
  66320. hierarchyIds.push(mesh.id);
  66321. return true;
  66322. }
  66323. }
  66324. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66325. hierarchyIds.push(mesh.id);
  66326. return true;
  66327. }
  66328. return false;
  66329. };
  66330. var logOperation = function (operation, producer) {
  66331. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66332. };
  66333. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66334. if (addToScene === void 0) { addToScene = false; }
  66335. var container = new BABYLON.AssetContainer(scene);
  66336. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66337. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66338. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66339. // and avoid problems with multiple concurrent .babylon loads.
  66340. var log = "importScene has failed JSON parse";
  66341. try {
  66342. var parsedData = JSON.parse(data);
  66343. log = "";
  66344. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66345. var index;
  66346. var cache;
  66347. // Lights
  66348. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66349. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66350. var parsedLight = parsedData.lights[index];
  66351. var light = BABYLON.Light.Parse(parsedLight, scene);
  66352. if (light) {
  66353. container.lights.push(light);
  66354. log += (index === 0 ? "\n\tLights:" : "");
  66355. log += "\n\t\t" + light.toString(fullDetails);
  66356. }
  66357. }
  66358. }
  66359. // Animations
  66360. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66361. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66362. var parsedAnimation = parsedData.animations[index];
  66363. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66364. scene.animations.push(animation);
  66365. container.animations.push(animation);
  66366. log += (index === 0 ? "\n\tAnimations:" : "");
  66367. log += "\n\t\t" + animation.toString(fullDetails);
  66368. }
  66369. }
  66370. // Materials
  66371. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66372. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66373. var parsedMaterial = parsedData.materials[index];
  66374. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66375. container.materials.push(mat);
  66376. log += (index === 0 ? "\n\tMaterials:" : "");
  66377. log += "\n\t\t" + mat.toString(fullDetails);
  66378. }
  66379. }
  66380. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66381. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66382. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66383. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66384. container.multiMaterials.push(mmat);
  66385. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66386. log += "\n\t\t" + mmat.toString(fullDetails);
  66387. }
  66388. }
  66389. // Morph targets
  66390. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66391. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66392. var managerData = _a[_i];
  66393. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66394. }
  66395. }
  66396. // Skeletons
  66397. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66398. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66399. var parsedSkeleton = parsedData.skeletons[index];
  66400. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66401. container.skeletons.push(skeleton);
  66402. log += (index === 0 ? "\n\tSkeletons:" : "");
  66403. log += "\n\t\t" + skeleton.toString(fullDetails);
  66404. }
  66405. }
  66406. // Geometries
  66407. var geometries = parsedData.geometries;
  66408. if (geometries !== undefined && geometries !== null) {
  66409. var addedGeometry = new Array();
  66410. // Boxes
  66411. var boxes = geometries.boxes;
  66412. if (boxes !== undefined && boxes !== null) {
  66413. for (index = 0, cache = boxes.length; index < cache; index++) {
  66414. var parsedBox = boxes[index];
  66415. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66416. }
  66417. }
  66418. // Spheres
  66419. var spheres = geometries.spheres;
  66420. if (spheres !== undefined && spheres !== null) {
  66421. for (index = 0, cache = spheres.length; index < cache; index++) {
  66422. var parsedSphere = spheres[index];
  66423. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66424. }
  66425. }
  66426. // Cylinders
  66427. var cylinders = geometries.cylinders;
  66428. if (cylinders !== undefined && cylinders !== null) {
  66429. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66430. var parsedCylinder = cylinders[index];
  66431. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66432. }
  66433. }
  66434. // Toruses
  66435. var toruses = geometries.toruses;
  66436. if (toruses !== undefined && toruses !== null) {
  66437. for (index = 0, cache = toruses.length; index < cache; index++) {
  66438. var parsedTorus = toruses[index];
  66439. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66440. }
  66441. }
  66442. // Grounds
  66443. var grounds = geometries.grounds;
  66444. if (grounds !== undefined && grounds !== null) {
  66445. for (index = 0, cache = grounds.length; index < cache; index++) {
  66446. var parsedGround = grounds[index];
  66447. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66448. }
  66449. }
  66450. // Planes
  66451. var planes = geometries.planes;
  66452. if (planes !== undefined && planes !== null) {
  66453. for (index = 0, cache = planes.length; index < cache; index++) {
  66454. var parsedPlane = planes[index];
  66455. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66456. }
  66457. }
  66458. // TorusKnots
  66459. var torusKnots = geometries.torusKnots;
  66460. if (torusKnots !== undefined && torusKnots !== null) {
  66461. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66462. var parsedTorusKnot = torusKnots[index];
  66463. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66464. }
  66465. }
  66466. // VertexData
  66467. var vertexData = geometries.vertexData;
  66468. if (vertexData !== undefined && vertexData !== null) {
  66469. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66470. var parsedVertexData = vertexData[index];
  66471. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66472. }
  66473. }
  66474. addedGeometry.forEach(function (g) {
  66475. if (g) {
  66476. container.geometries.push(g);
  66477. }
  66478. });
  66479. }
  66480. // Transform nodes
  66481. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66482. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66483. var parsedTransformNode = parsedData.transformNodes[index];
  66484. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66485. container.transformNodes.push(node);
  66486. }
  66487. }
  66488. // Meshes
  66489. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66490. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66491. var parsedMesh = parsedData.meshes[index];
  66492. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66493. container.meshes.push(mesh);
  66494. log += (index === 0 ? "\n\tMeshes:" : "");
  66495. log += "\n\t\t" + mesh.toString(fullDetails);
  66496. }
  66497. }
  66498. // Cameras
  66499. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66500. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66501. var parsedCamera = parsedData.cameras[index];
  66502. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66503. container.cameras.push(camera);
  66504. log += (index === 0 ? "\n\tCameras:" : "");
  66505. log += "\n\t\t" + camera.toString(fullDetails);
  66506. }
  66507. }
  66508. // Browsing all the graph to connect the dots
  66509. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66510. var camera = scene.cameras[index];
  66511. if (camera._waitingParentId) {
  66512. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66513. camera._waitingParentId = null;
  66514. }
  66515. }
  66516. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66517. var light_1 = scene.lights[index];
  66518. if (light_1 && light_1._waitingParentId) {
  66519. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66520. light_1._waitingParentId = null;
  66521. }
  66522. }
  66523. // Sounds
  66524. // TODO: add sound
  66525. var loadedSounds = [];
  66526. var loadedSound;
  66527. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66528. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66529. var parsedSound = parsedData.sounds[index];
  66530. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66531. if (!parsedSound.url)
  66532. parsedSound.url = parsedSound.name;
  66533. if (!loadedSounds[parsedSound.url]) {
  66534. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66535. loadedSounds[parsedSound.url] = loadedSound;
  66536. container.sounds.push(loadedSound);
  66537. }
  66538. else {
  66539. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66540. }
  66541. }
  66542. else {
  66543. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66544. }
  66545. }
  66546. }
  66547. loadedSounds = [];
  66548. // Connect parents & children and parse actions
  66549. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66550. var transformNode = scene.transformNodes[index];
  66551. if (transformNode._waitingParentId) {
  66552. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66553. transformNode._waitingParentId = null;
  66554. }
  66555. }
  66556. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66557. var mesh = scene.meshes[index];
  66558. if (mesh._waitingParentId) {
  66559. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66560. mesh._waitingParentId = null;
  66561. }
  66562. if (mesh._waitingActions) {
  66563. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66564. mesh._waitingActions = null;
  66565. }
  66566. }
  66567. // freeze world matrix application
  66568. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66569. var currentMesh = scene.meshes[index];
  66570. if (currentMesh._waitingFreezeWorldMatrix) {
  66571. currentMesh.freezeWorldMatrix();
  66572. currentMesh._waitingFreezeWorldMatrix = null;
  66573. }
  66574. else {
  66575. currentMesh.computeWorldMatrix(true);
  66576. }
  66577. }
  66578. // Particles Systems
  66579. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66580. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66581. var parsedParticleSystem = parsedData.particleSystems[index];
  66582. if (parsedParticleSystem.activeParticleCount) {
  66583. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66584. container.particleSystems.push(ps);
  66585. }
  66586. else {
  66587. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66588. container.particleSystems.push(ps);
  66589. }
  66590. }
  66591. }
  66592. // Lens flares
  66593. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66594. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66595. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66596. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66597. container.lensFlareSystems.push(lf);
  66598. }
  66599. }
  66600. // Shadows
  66601. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66602. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66603. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66604. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66605. container.shadowGenerators.push(sg);
  66606. }
  66607. }
  66608. // Lights exclusions / inclusions
  66609. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66610. var light_2 = scene.lights[index];
  66611. // Excluded check
  66612. if (light_2._excludedMeshesIds.length > 0) {
  66613. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66614. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66615. if (excludedMesh) {
  66616. light_2.excludedMeshes.push(excludedMesh);
  66617. }
  66618. }
  66619. light_2._excludedMeshesIds = [];
  66620. }
  66621. // Included check
  66622. if (light_2._includedOnlyMeshesIds.length > 0) {
  66623. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66624. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66625. if (includedOnlyMesh) {
  66626. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66627. }
  66628. }
  66629. light_2._includedOnlyMeshesIds = [];
  66630. }
  66631. }
  66632. // Effect layers
  66633. if (parsedData.effectLayers) {
  66634. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66635. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66636. container.effectLayers.push(effectLayer);
  66637. }
  66638. }
  66639. // Actions (scene)
  66640. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66641. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66642. }
  66643. if (!addToScene) {
  66644. container.removeAllFromScene();
  66645. }
  66646. }
  66647. catch (err) {
  66648. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66649. if (onError) {
  66650. onError(msg, err);
  66651. }
  66652. else {
  66653. BABYLON.Tools.Log(msg);
  66654. throw err;
  66655. }
  66656. }
  66657. finally {
  66658. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66659. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66660. }
  66661. }
  66662. return container;
  66663. };
  66664. BABYLON.SceneLoader.RegisterPlugin({
  66665. name: "babylon.js",
  66666. extensions: ".babylon",
  66667. canDirectLoad: function (data) {
  66668. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  66669. return true;
  66670. }
  66671. return false;
  66672. },
  66673. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66674. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66675. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66676. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66677. // and avoid problems with multiple concurrent .babylon loads.
  66678. var log = "importMesh has failed JSON parse";
  66679. try {
  66680. var parsedData = JSON.parse(data);
  66681. log = "";
  66682. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66683. if (!meshesNames) {
  66684. meshesNames = null;
  66685. }
  66686. else if (!Array.isArray(meshesNames)) {
  66687. meshesNames = [meshesNames];
  66688. }
  66689. var hierarchyIds = new Array();
  66690. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66691. var loadedSkeletonsIds = [];
  66692. var loadedMaterialsIds = [];
  66693. var index;
  66694. var cache;
  66695. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66696. var parsedMesh = parsedData.meshes[index];
  66697. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66698. if (meshesNames !== null) {
  66699. // Remove found mesh name from list.
  66700. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66701. }
  66702. //Geometry?
  66703. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66704. //does the file contain geometries?
  66705. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66706. //find the correct geometry and add it to the scene
  66707. var found = false;
  66708. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66709. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66710. return;
  66711. }
  66712. else {
  66713. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66714. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66715. switch (geometryType) {
  66716. case "boxes":
  66717. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66718. break;
  66719. case "spheres":
  66720. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66721. break;
  66722. case "cylinders":
  66723. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66724. break;
  66725. case "toruses":
  66726. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66727. break;
  66728. case "grounds":
  66729. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66730. break;
  66731. case "planes":
  66732. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66733. break;
  66734. case "torusKnots":
  66735. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66736. break;
  66737. case "vertexData":
  66738. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66739. break;
  66740. }
  66741. found = true;
  66742. }
  66743. });
  66744. }
  66745. });
  66746. if (found === false) {
  66747. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66748. }
  66749. }
  66750. }
  66751. // Material ?
  66752. if (parsedMesh.materialId) {
  66753. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66754. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66755. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66756. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66757. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66758. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66759. var subMatId = parsedMultiMaterial.materials[matIndex];
  66760. loadedMaterialsIds.push(subMatId);
  66761. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66762. if (mat) {
  66763. log += "\n\tMaterial " + mat.toString(fullDetails);
  66764. }
  66765. }
  66766. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66767. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66768. if (mmat) {
  66769. materialFound = true;
  66770. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66771. }
  66772. break;
  66773. }
  66774. }
  66775. }
  66776. if (materialFound === false) {
  66777. loadedMaterialsIds.push(parsedMesh.materialId);
  66778. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66779. if (!mat) {
  66780. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66781. }
  66782. else {
  66783. log += "\n\tMaterial " + mat.toString(fullDetails);
  66784. }
  66785. }
  66786. }
  66787. // Skeleton ?
  66788. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66789. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66790. if (skeletonAlreadyLoaded === false) {
  66791. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66792. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66793. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66794. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66795. skeletons.push(skeleton);
  66796. loadedSkeletonsIds.push(parsedSkeleton.id);
  66797. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66798. }
  66799. }
  66800. }
  66801. }
  66802. // Morph targets ?
  66803. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66804. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66805. var managerData = _a[_i];
  66806. BABYLON.MorphTargetManager.Parse(managerData, scene);
  66807. }
  66808. }
  66809. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66810. meshes.push(mesh);
  66811. log += "\n\tMesh " + mesh.toString(fullDetails);
  66812. }
  66813. }
  66814. // Connecting parents
  66815. var currentMesh;
  66816. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66817. currentMesh = scene.meshes[index];
  66818. if (currentMesh._waitingParentId) {
  66819. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66820. currentMesh._waitingParentId = null;
  66821. }
  66822. }
  66823. // freeze and compute world matrix application
  66824. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66825. currentMesh = scene.meshes[index];
  66826. if (currentMesh._waitingFreezeWorldMatrix) {
  66827. currentMesh.freezeWorldMatrix();
  66828. currentMesh._waitingFreezeWorldMatrix = null;
  66829. }
  66830. else {
  66831. currentMesh.computeWorldMatrix(true);
  66832. }
  66833. }
  66834. }
  66835. // Particles
  66836. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66837. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66838. var parsedParticleSystem = parsedData.particleSystems[index];
  66839. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66840. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66841. }
  66842. }
  66843. }
  66844. return true;
  66845. }
  66846. catch (err) {
  66847. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66848. if (onError) {
  66849. onError(msg, err);
  66850. }
  66851. else {
  66852. BABYLON.Tools.Log(msg);
  66853. throw err;
  66854. }
  66855. }
  66856. finally {
  66857. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66858. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66859. }
  66860. }
  66861. return false;
  66862. },
  66863. load: function (scene, data, rootUrl, onError) {
  66864. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66865. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66866. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66867. // and avoid problems with multiple concurrent .babylon loads.
  66868. var log = "importScene has failed JSON parse";
  66869. try {
  66870. var parsedData = JSON.parse(data);
  66871. log = "";
  66872. // Scene
  66873. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66874. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66875. }
  66876. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66877. scene.autoClear = parsedData.autoClear;
  66878. }
  66879. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66880. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66881. }
  66882. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66883. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66884. }
  66885. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66886. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66887. }
  66888. // Fog
  66889. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66890. scene.fogMode = parsedData.fogMode;
  66891. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66892. scene.fogStart = parsedData.fogStart;
  66893. scene.fogEnd = parsedData.fogEnd;
  66894. scene.fogDensity = parsedData.fogDensity;
  66895. log += "\tFog mode for scene: ";
  66896. switch (scene.fogMode) {
  66897. // getters not compiling, so using hardcoded
  66898. case 1:
  66899. log += "exp\n";
  66900. break;
  66901. case 2:
  66902. log += "exp2\n";
  66903. break;
  66904. case 3:
  66905. log += "linear\n";
  66906. break;
  66907. }
  66908. }
  66909. //Physics
  66910. if (parsedData.physicsEnabled) {
  66911. var physicsPlugin;
  66912. if (parsedData.physicsEngine === "cannon") {
  66913. physicsPlugin = new BABYLON.CannonJSPlugin();
  66914. }
  66915. else if (parsedData.physicsEngine === "oimo") {
  66916. physicsPlugin = new BABYLON.OimoJSPlugin();
  66917. }
  66918. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66919. //else - default engine, which is currently oimo
  66920. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66921. scene.enablePhysics(physicsGravity, physicsPlugin);
  66922. }
  66923. // Metadata
  66924. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66925. scene.metadata = parsedData.metadata;
  66926. }
  66927. //collisions, if defined. otherwise, default is true
  66928. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66929. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66930. }
  66931. scene.workerCollisions = !!parsedData.workerCollisions;
  66932. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66933. if (!container) {
  66934. return false;
  66935. }
  66936. if (parsedData.autoAnimate) {
  66937. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66938. }
  66939. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66940. scene.setActiveCameraByID(parsedData.activeCameraID);
  66941. }
  66942. // Environment texture
  66943. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66944. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66945. if (parsedData.createDefaultSkybox === true) {
  66946. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66947. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66948. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66949. }
  66950. }
  66951. // Finish
  66952. return true;
  66953. }
  66954. catch (err) {
  66955. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66956. if (onError) {
  66957. onError(msg, err);
  66958. }
  66959. else {
  66960. BABYLON.Tools.Log(msg);
  66961. throw err;
  66962. }
  66963. }
  66964. finally {
  66965. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66966. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66967. }
  66968. }
  66969. return false;
  66970. },
  66971. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66972. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66973. return container;
  66974. }
  66975. });
  66976. })(BABYLON || (BABYLON = {}));
  66977. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66978. var BABYLON;
  66979. (function (BABYLON) {
  66980. var FilesInput = /** @class */ (function () {
  66981. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66982. this.onProcessFileCallback = function () { return true; };
  66983. this._engine = engine;
  66984. this._currentScene = scene;
  66985. this._sceneLoadedCallback = sceneLoadedCallback;
  66986. this._progressCallback = progressCallback;
  66987. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66988. this._textureLoadingCallback = textureLoadingCallback;
  66989. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66990. this._onReloadCallback = onReloadCallback;
  66991. this._errorCallback = errorCallback;
  66992. }
  66993. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66994. var _this = this;
  66995. if (elementToMonitor) {
  66996. this._elementToMonitor = elementToMonitor;
  66997. this._dragEnterHandler = function (e) { _this.drag(e); };
  66998. this._dragOverHandler = function (e) { _this.drag(e); };
  66999. this._dropHandler = function (e) { _this.drop(e); };
  67000. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67001. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67002. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67003. }
  67004. };
  67005. FilesInput.prototype.dispose = function () {
  67006. if (!this._elementToMonitor) {
  67007. return;
  67008. }
  67009. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67010. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67011. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67012. };
  67013. FilesInput.prototype.renderFunction = function () {
  67014. if (this._additionalRenderLoopLogicCallback) {
  67015. this._additionalRenderLoopLogicCallback();
  67016. }
  67017. if (this._currentScene) {
  67018. if (this._textureLoadingCallback) {
  67019. var remaining = this._currentScene.getWaitingItemsCount();
  67020. if (remaining > 0) {
  67021. this._textureLoadingCallback(remaining);
  67022. }
  67023. }
  67024. this._currentScene.render();
  67025. }
  67026. };
  67027. FilesInput.prototype.drag = function (e) {
  67028. e.stopPropagation();
  67029. e.preventDefault();
  67030. };
  67031. FilesInput.prototype.drop = function (eventDrop) {
  67032. eventDrop.stopPropagation();
  67033. eventDrop.preventDefault();
  67034. this.loadFiles(eventDrop);
  67035. };
  67036. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67037. var _this = this;
  67038. var reader = folder.createReader();
  67039. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67040. reader.readEntries(function (entries) {
  67041. remaining.count += entries.length;
  67042. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67043. var entry = entries_1[_i];
  67044. if (entry.isFile) {
  67045. entry.file(function (file) {
  67046. file.correctName = relativePath + file.name;
  67047. files.push(file);
  67048. if (--remaining.count === 0) {
  67049. callback();
  67050. }
  67051. });
  67052. }
  67053. else if (entry.isDirectory) {
  67054. _this._traverseFolder(entry, files, remaining, callback);
  67055. }
  67056. }
  67057. if (--remaining.count) {
  67058. callback();
  67059. }
  67060. });
  67061. };
  67062. FilesInput.prototype._processFiles = function (files) {
  67063. for (var i = 0; i < files.length; i++) {
  67064. var name = files[i].correctName.toLowerCase();
  67065. var extension = name.split('.').pop();
  67066. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67067. continue;
  67068. }
  67069. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67070. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67071. this._sceneFileToLoad = files[i];
  67072. }
  67073. else {
  67074. FilesInput.FilesToLoad[name] = files[i];
  67075. }
  67076. }
  67077. };
  67078. FilesInput.prototype.loadFiles = function (event) {
  67079. var _this = this;
  67080. if (this._startingProcessingFilesCallback)
  67081. this._startingProcessingFilesCallback();
  67082. // Handling data transfer via drag'n'drop
  67083. if (event && event.dataTransfer && event.dataTransfer.files) {
  67084. this._filesToLoad = event.dataTransfer.files;
  67085. }
  67086. // Handling files from input files
  67087. if (event && event.target && event.target.files) {
  67088. this._filesToLoad = event.target.files;
  67089. }
  67090. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67091. var files_1 = new Array();
  67092. var folders = [];
  67093. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67094. for (var i = 0; i < this._filesToLoad.length; i++) {
  67095. var fileToLoad = this._filesToLoad[i];
  67096. var name_1 = fileToLoad.name.toLowerCase();
  67097. var entry = void 0;
  67098. fileToLoad.correctName = name_1;
  67099. if (items) {
  67100. var item = items[i];
  67101. if (item.getAsEntry) {
  67102. entry = item.getAsEntry();
  67103. }
  67104. else if (item.webkitGetAsEntry) {
  67105. entry = item.webkitGetAsEntry();
  67106. }
  67107. }
  67108. if (!entry) {
  67109. files_1.push(fileToLoad);
  67110. }
  67111. else {
  67112. if (entry.isDirectory) {
  67113. folders.push(entry);
  67114. }
  67115. else {
  67116. files_1.push(fileToLoad);
  67117. }
  67118. }
  67119. }
  67120. if (folders.length === 0) {
  67121. this._processFiles(files_1);
  67122. this._processReload();
  67123. }
  67124. else {
  67125. var remaining = { count: folders.length };
  67126. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67127. var folder = folders_1[_i];
  67128. this._traverseFolder(folder, files_1, remaining, function () {
  67129. _this._processFiles(files_1);
  67130. if (remaining.count === 0) {
  67131. _this._processReload();
  67132. }
  67133. });
  67134. }
  67135. }
  67136. }
  67137. };
  67138. FilesInput.prototype._processReload = function () {
  67139. if (this._onReloadCallback) {
  67140. this._onReloadCallback(this._sceneFileToLoad);
  67141. }
  67142. else {
  67143. this.reload();
  67144. }
  67145. };
  67146. FilesInput.prototype.reload = function () {
  67147. var _this = this;
  67148. // If a scene file has been provided
  67149. if (this._sceneFileToLoad) {
  67150. if (this._currentScene) {
  67151. if (BABYLON.Tools.errorsCount > 0) {
  67152. BABYLON.Tools.ClearLogCache();
  67153. }
  67154. this._engine.stopRenderLoop();
  67155. this._currentScene.dispose();
  67156. }
  67157. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67158. if (_this._progressCallback) {
  67159. _this._progressCallback(progress);
  67160. }
  67161. }).then(function (scene) {
  67162. _this._currentScene = scene;
  67163. if (_this._sceneLoadedCallback) {
  67164. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67165. }
  67166. // Wait for textures and shaders to be ready
  67167. _this._currentScene.executeWhenReady(function () {
  67168. _this._engine.runRenderLoop(function () {
  67169. _this.renderFunction();
  67170. });
  67171. });
  67172. }).catch(function (error) {
  67173. if (_this._errorCallback) {
  67174. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67175. }
  67176. });
  67177. }
  67178. else {
  67179. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67180. }
  67181. };
  67182. FilesInput.FilesToLoad = {};
  67183. return FilesInput;
  67184. }());
  67185. BABYLON.FilesInput = FilesInput;
  67186. })(BABYLON || (BABYLON = {}));
  67187. //# sourceMappingURL=babylon.filesInput.js.map
  67188. var BABYLON;
  67189. (function (BABYLON) {
  67190. /**
  67191. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67192. * The underlying implementation relies on an associative array to ensure the best performances.
  67193. * The value can be anything including 'null' but except 'undefined'
  67194. */
  67195. var StringDictionary = /** @class */ (function () {
  67196. function StringDictionary() {
  67197. this._count = 0;
  67198. this._data = {};
  67199. }
  67200. /**
  67201. * This will clear this dictionary and copy the content from the 'source' one.
  67202. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67203. * @param source the dictionary to take the content from and copy to this dictionary
  67204. */
  67205. StringDictionary.prototype.copyFrom = function (source) {
  67206. var _this = this;
  67207. this.clear();
  67208. source.forEach(function (t, v) { return _this.add(t, v); });
  67209. };
  67210. /**
  67211. * Get a value based from its key
  67212. * @param key the given key to get the matching value from
  67213. * @return the value if found, otherwise undefined is returned
  67214. */
  67215. StringDictionary.prototype.get = function (key) {
  67216. var val = this._data[key];
  67217. if (val !== undefined) {
  67218. return val;
  67219. }
  67220. return undefined;
  67221. };
  67222. /**
  67223. * Get a value from its key or add it if it doesn't exist.
  67224. * This method will ensure you that a given key/data will be present in the dictionary.
  67225. * @param key the given key to get the matching value from
  67226. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67227. * The factory will only be invoked if there's no data for the given key.
  67228. * @return the value corresponding to the key.
  67229. */
  67230. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67231. var val = this.get(key);
  67232. if (val !== undefined) {
  67233. return val;
  67234. }
  67235. val = factory(key);
  67236. if (val) {
  67237. this.add(key, val);
  67238. }
  67239. return val;
  67240. };
  67241. /**
  67242. * Get a value from its key if present in the dictionary otherwise add it
  67243. * @param key the key to get the value from
  67244. * @param val if there's no such key/value pair in the dictionary add it with this value
  67245. * @return the value corresponding to the key
  67246. */
  67247. StringDictionary.prototype.getOrAdd = function (key, val) {
  67248. var curVal = this.get(key);
  67249. if (curVal !== undefined) {
  67250. return curVal;
  67251. }
  67252. this.add(key, val);
  67253. return val;
  67254. };
  67255. /**
  67256. * Check if there's a given key in the dictionary
  67257. * @param key the key to check for
  67258. * @return true if the key is present, false otherwise
  67259. */
  67260. StringDictionary.prototype.contains = function (key) {
  67261. return this._data[key] !== undefined;
  67262. };
  67263. /**
  67264. * Add a new key and its corresponding value
  67265. * @param key the key to add
  67266. * @param value the value corresponding to the key
  67267. * @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
  67268. */
  67269. StringDictionary.prototype.add = function (key, value) {
  67270. if (this._data[key] !== undefined) {
  67271. return false;
  67272. }
  67273. this._data[key] = value;
  67274. ++this._count;
  67275. return true;
  67276. };
  67277. StringDictionary.prototype.set = function (key, value) {
  67278. if (this._data[key] === undefined) {
  67279. return false;
  67280. }
  67281. this._data[key] = value;
  67282. return true;
  67283. };
  67284. /**
  67285. * Get the element of the given key and remove it from the dictionary
  67286. * @param key
  67287. */
  67288. StringDictionary.prototype.getAndRemove = function (key) {
  67289. var val = this.get(key);
  67290. if (val !== undefined) {
  67291. delete this._data[key];
  67292. --this._count;
  67293. return val;
  67294. }
  67295. return null;
  67296. };
  67297. /**
  67298. * Remove a key/value from the dictionary.
  67299. * @param key the key to remove
  67300. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67301. */
  67302. StringDictionary.prototype.remove = function (key) {
  67303. if (this.contains(key)) {
  67304. delete this._data[key];
  67305. --this._count;
  67306. return true;
  67307. }
  67308. return false;
  67309. };
  67310. /**
  67311. * Clear the whole content of the dictionary
  67312. */
  67313. StringDictionary.prototype.clear = function () {
  67314. this._data = {};
  67315. this._count = 0;
  67316. };
  67317. Object.defineProperty(StringDictionary.prototype, "count", {
  67318. get: function () {
  67319. return this._count;
  67320. },
  67321. enumerable: true,
  67322. configurable: true
  67323. });
  67324. /**
  67325. * Execute a callback on each key/val of the dictionary.
  67326. * Note that you can remove any element in this dictionary in the callback implementation
  67327. * @param callback the callback to execute on a given key/value pair
  67328. */
  67329. StringDictionary.prototype.forEach = function (callback) {
  67330. for (var cur in this._data) {
  67331. var val = this._data[cur];
  67332. callback(cur, val);
  67333. }
  67334. };
  67335. /**
  67336. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67337. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67338. * Note that you can remove any element in this dictionary in the callback implementation
  67339. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67340. */
  67341. StringDictionary.prototype.first = function (callback) {
  67342. for (var cur in this._data) {
  67343. var val = this._data[cur];
  67344. var res = callback(cur, val);
  67345. if (res) {
  67346. return res;
  67347. }
  67348. }
  67349. return null;
  67350. };
  67351. return StringDictionary;
  67352. }());
  67353. BABYLON.StringDictionary = StringDictionary;
  67354. })(BABYLON || (BABYLON = {}));
  67355. //# sourceMappingURL=babylon.stringDictionary.js.map
  67356. var BABYLON;
  67357. (function (BABYLON) {
  67358. var Tags = /** @class */ (function () {
  67359. function Tags() {
  67360. }
  67361. Tags.EnableFor = function (obj) {
  67362. obj._tags = obj._tags || {};
  67363. obj.hasTags = function () {
  67364. return Tags.HasTags(obj);
  67365. };
  67366. obj.addTags = function (tagsString) {
  67367. return Tags.AddTagsTo(obj, tagsString);
  67368. };
  67369. obj.removeTags = function (tagsString) {
  67370. return Tags.RemoveTagsFrom(obj, tagsString);
  67371. };
  67372. obj.matchesTagsQuery = function (tagsQuery) {
  67373. return Tags.MatchesQuery(obj, tagsQuery);
  67374. };
  67375. };
  67376. Tags.DisableFor = function (obj) {
  67377. delete obj._tags;
  67378. delete obj.hasTags;
  67379. delete obj.addTags;
  67380. delete obj.removeTags;
  67381. delete obj.matchesTagsQuery;
  67382. };
  67383. Tags.HasTags = function (obj) {
  67384. if (!obj._tags) {
  67385. return false;
  67386. }
  67387. return !BABYLON.Tools.IsEmpty(obj._tags);
  67388. };
  67389. Tags.GetTags = function (obj, asString) {
  67390. if (asString === void 0) { asString = true; }
  67391. if (!obj._tags) {
  67392. return null;
  67393. }
  67394. if (asString) {
  67395. var tagsArray = [];
  67396. for (var tag in obj._tags) {
  67397. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67398. tagsArray.push(tag);
  67399. }
  67400. }
  67401. return tagsArray.join(" ");
  67402. }
  67403. else {
  67404. return obj._tags;
  67405. }
  67406. };
  67407. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67408. // a tag cannot start with '||', '&&', and '!'
  67409. // it cannot contain whitespaces
  67410. Tags.AddTagsTo = function (obj, tagsString) {
  67411. if (!tagsString) {
  67412. return;
  67413. }
  67414. if (typeof tagsString !== "string") {
  67415. return;
  67416. }
  67417. var tags = tagsString.split(" ");
  67418. tags.forEach(function (tag, index, array) {
  67419. Tags._AddTagTo(obj, tag);
  67420. });
  67421. };
  67422. Tags._AddTagTo = function (obj, tag) {
  67423. tag = tag.trim();
  67424. if (tag === "" || tag === "true" || tag === "false") {
  67425. return;
  67426. }
  67427. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67428. return;
  67429. }
  67430. Tags.EnableFor(obj);
  67431. obj._tags[tag] = true;
  67432. };
  67433. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67434. if (!Tags.HasTags(obj)) {
  67435. return;
  67436. }
  67437. var tags = tagsString.split(" ");
  67438. for (var t in tags) {
  67439. Tags._RemoveTagFrom(obj, tags[t]);
  67440. }
  67441. };
  67442. Tags._RemoveTagFrom = function (obj, tag) {
  67443. delete obj._tags[tag];
  67444. };
  67445. Tags.MatchesQuery = function (obj, tagsQuery) {
  67446. if (tagsQuery === undefined) {
  67447. return true;
  67448. }
  67449. if (tagsQuery === "") {
  67450. return Tags.HasTags(obj);
  67451. }
  67452. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67453. };
  67454. return Tags;
  67455. }());
  67456. BABYLON.Tags = Tags;
  67457. })(BABYLON || (BABYLON = {}));
  67458. //# sourceMappingURL=babylon.tags.js.map
  67459. var BABYLON;
  67460. (function (BABYLON) {
  67461. var AndOrNotEvaluator = /** @class */ (function () {
  67462. function AndOrNotEvaluator() {
  67463. }
  67464. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67465. if (!query.match(/\([^\(\)]*\)/g)) {
  67466. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67467. }
  67468. else {
  67469. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67470. // remove parenthesis
  67471. r = r.slice(1, r.length - 1);
  67472. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67473. });
  67474. }
  67475. if (query === "true") {
  67476. return true;
  67477. }
  67478. if (query === "false") {
  67479. return false;
  67480. }
  67481. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67482. };
  67483. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67484. evaluateCallback = evaluateCallback || (function (r) {
  67485. return r === "true" ? true : false;
  67486. });
  67487. var result;
  67488. var or = parenthesisContent.split("||");
  67489. for (var i in or) {
  67490. if (or.hasOwnProperty(i)) {
  67491. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67492. var and = ori.split("&&");
  67493. if (and.length > 1) {
  67494. for (var j = 0; j < and.length; ++j) {
  67495. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67496. if (andj !== "true" && andj !== "false") {
  67497. if (andj[0] === "!") {
  67498. result = !evaluateCallback(andj.substring(1));
  67499. }
  67500. else {
  67501. result = evaluateCallback(andj);
  67502. }
  67503. }
  67504. else {
  67505. result = andj === "true" ? true : false;
  67506. }
  67507. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  67508. ori = "false";
  67509. break;
  67510. }
  67511. }
  67512. }
  67513. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  67514. result = true;
  67515. break;
  67516. }
  67517. // result equals false (or undefined)
  67518. if (ori !== "true" && ori !== "false") {
  67519. if (ori[0] === "!") {
  67520. result = !evaluateCallback(ori.substring(1));
  67521. }
  67522. else {
  67523. result = evaluateCallback(ori);
  67524. }
  67525. }
  67526. else {
  67527. result = ori === "true" ? true : false;
  67528. }
  67529. }
  67530. }
  67531. // the whole parenthesis scope is replaced by 'true' or 'false'
  67532. return result ? "true" : "false";
  67533. };
  67534. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67535. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67536. // remove whitespaces
  67537. r = r.replace(/[\s]/g, function () { return ""; });
  67538. return r.length % 2 ? "!" : "";
  67539. });
  67540. booleanString = booleanString.trim();
  67541. if (booleanString === "!true") {
  67542. booleanString = "false";
  67543. }
  67544. else if (booleanString === "!false") {
  67545. booleanString = "true";
  67546. }
  67547. return booleanString;
  67548. };
  67549. return AndOrNotEvaluator;
  67550. }());
  67551. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67552. })(BABYLON || (BABYLON = {}));
  67553. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67554. var BABYLON;
  67555. (function (BABYLON) {
  67556. var Database = /** @class */ (function () {
  67557. function Database(urlToScene, callbackManifestChecked) {
  67558. // Handling various flavors of prefixed version of IndexedDB
  67559. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67560. this.callbackManifestChecked = callbackManifestChecked;
  67561. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67562. this.db = null;
  67563. this._enableSceneOffline = false;
  67564. this._enableTexturesOffline = false;
  67565. this.manifestVersionFound = 0;
  67566. this.mustUpdateRessources = false;
  67567. this.hasReachedQuota = false;
  67568. if (!Database.IDBStorageEnabled) {
  67569. this.callbackManifestChecked(true);
  67570. }
  67571. else {
  67572. this.checkManifestFile();
  67573. }
  67574. }
  67575. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67576. get: function () {
  67577. return this._enableSceneOffline;
  67578. },
  67579. enumerable: true,
  67580. configurable: true
  67581. });
  67582. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67583. get: function () {
  67584. return this._enableTexturesOffline;
  67585. },
  67586. enumerable: true,
  67587. configurable: true
  67588. });
  67589. Database.prototype.checkManifestFile = function () {
  67590. var _this = this;
  67591. var noManifestFile = function () {
  67592. _this._enableSceneOffline = false;
  67593. _this._enableTexturesOffline = false;
  67594. _this.callbackManifestChecked(false);
  67595. };
  67596. var timeStampUsed = false;
  67597. var manifestURL = this.currentSceneUrl + ".manifest";
  67598. var xhr = new XMLHttpRequest();
  67599. if (navigator.onLine) {
  67600. // Adding a timestamp to by-pass browsers' cache
  67601. timeStampUsed = true;
  67602. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67603. }
  67604. xhr.open("GET", manifestURL, true);
  67605. xhr.addEventListener("load", function () {
  67606. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67607. try {
  67608. var manifestFile = JSON.parse(xhr.response);
  67609. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67610. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67611. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67612. _this.manifestVersionFound = manifestFile.version;
  67613. }
  67614. if (_this.callbackManifestChecked) {
  67615. _this.callbackManifestChecked(true);
  67616. }
  67617. }
  67618. catch (ex) {
  67619. noManifestFile();
  67620. }
  67621. }
  67622. else {
  67623. noManifestFile();
  67624. }
  67625. }, false);
  67626. xhr.addEventListener("error", function (event) {
  67627. if (timeStampUsed) {
  67628. timeStampUsed = false;
  67629. // Let's retry without the timeStamp
  67630. // It could fail when coupled with HTML5 Offline API
  67631. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67632. xhr.open("GET", retryManifestURL, true);
  67633. xhr.send();
  67634. }
  67635. else {
  67636. noManifestFile();
  67637. }
  67638. }, false);
  67639. try {
  67640. xhr.send();
  67641. }
  67642. catch (ex) {
  67643. BABYLON.Tools.Error("Error on XHR send request.");
  67644. this.callbackManifestChecked(false);
  67645. }
  67646. };
  67647. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67648. var _this = this;
  67649. var handleError = function () {
  67650. _this.isSupported = false;
  67651. if (errorCallback)
  67652. errorCallback();
  67653. };
  67654. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67655. // Your browser doesn't support IndexedDB
  67656. this.isSupported = false;
  67657. if (errorCallback)
  67658. errorCallback();
  67659. }
  67660. else {
  67661. // If the DB hasn't been opened or created yet
  67662. if (!this.db) {
  67663. this.hasReachedQuota = false;
  67664. this.isSupported = true;
  67665. var request = this.idbFactory.open("babylonjs", 1);
  67666. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67667. request.onerror = function (event) {
  67668. handleError();
  67669. };
  67670. // executes when a version change transaction cannot complete due to other active transactions
  67671. request.onblocked = function (event) {
  67672. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67673. handleError();
  67674. };
  67675. // DB has been opened successfully
  67676. request.onsuccess = function (event) {
  67677. _this.db = request.result;
  67678. successCallback();
  67679. };
  67680. // Initialization of the DB. Creating Scenes & Textures stores
  67681. request.onupgradeneeded = function (event) {
  67682. _this.db = (event.target).result;
  67683. if (_this.db) {
  67684. try {
  67685. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67686. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67687. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67688. }
  67689. catch (ex) {
  67690. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67691. handleError();
  67692. }
  67693. }
  67694. };
  67695. }
  67696. // DB has already been created and opened
  67697. else {
  67698. if (successCallback)
  67699. successCallback();
  67700. }
  67701. }
  67702. };
  67703. Database.prototype.loadImageFromDB = function (url, image) {
  67704. var _this = this;
  67705. var completeURL = Database.ReturnFullUrlLocation(url);
  67706. var saveAndLoadImage = function () {
  67707. if (!_this.hasReachedQuota && _this.db !== null) {
  67708. // the texture is not yet in the DB, let's try to save it
  67709. _this._saveImageIntoDBAsync(completeURL, image);
  67710. }
  67711. // If the texture is not in the DB and we've reached the DB quota limit
  67712. // let's load it directly from the web
  67713. else {
  67714. image.src = url;
  67715. }
  67716. };
  67717. if (!this.mustUpdateRessources) {
  67718. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67719. }
  67720. // First time we're download the images or update requested in the manifest file by a version change
  67721. else {
  67722. saveAndLoadImage();
  67723. }
  67724. };
  67725. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67726. if (this.isSupported && this.db !== null) {
  67727. var texture;
  67728. var transaction = this.db.transaction(["textures"]);
  67729. transaction.onabort = function (event) {
  67730. image.src = url;
  67731. };
  67732. transaction.oncomplete = function (event) {
  67733. var blobTextureURL;
  67734. if (texture) {
  67735. var URL = window.URL || window.webkitURL;
  67736. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67737. image.onerror = function () {
  67738. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67739. image.src = url;
  67740. };
  67741. image.src = blobTextureURL;
  67742. }
  67743. else {
  67744. notInDBCallback();
  67745. }
  67746. };
  67747. var getRequest = transaction.objectStore("textures").get(url);
  67748. getRequest.onsuccess = function (event) {
  67749. texture = (event.target).result;
  67750. };
  67751. getRequest.onerror = function (event) {
  67752. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67753. image.src = url;
  67754. };
  67755. }
  67756. else {
  67757. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67758. image.src = url;
  67759. }
  67760. };
  67761. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67762. var _this = this;
  67763. if (this.isSupported) {
  67764. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67765. var generateBlobUrl = function () {
  67766. var blobTextureURL;
  67767. if (blob) {
  67768. var URL = window.URL || window.webkitURL;
  67769. try {
  67770. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67771. }
  67772. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67773. catch (ex) {
  67774. blobTextureURL = URL.createObjectURL(blob);
  67775. }
  67776. }
  67777. if (blobTextureURL) {
  67778. image.src = blobTextureURL;
  67779. }
  67780. };
  67781. if (Database.IsUASupportingBlobStorage) { // Create XHR
  67782. var xhr = new XMLHttpRequest(), blob;
  67783. xhr.open("GET", url, true);
  67784. xhr.responseType = "blob";
  67785. xhr.addEventListener("load", function () {
  67786. if (xhr.status === 200 && _this.db) {
  67787. // Blob as response (XHR2)
  67788. blob = xhr.response;
  67789. var transaction = _this.db.transaction(["textures"], "readwrite");
  67790. // the transaction could abort because of a QuotaExceededError error
  67791. transaction.onabort = function (event) {
  67792. try {
  67793. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67794. var srcElement = (event.srcElement || event.target);
  67795. var error = srcElement.error;
  67796. if (error && error.name === "QuotaExceededError") {
  67797. _this.hasReachedQuota = true;
  67798. }
  67799. }
  67800. catch (ex) { }
  67801. generateBlobUrl();
  67802. };
  67803. transaction.oncomplete = function (event) {
  67804. generateBlobUrl();
  67805. };
  67806. var newTexture = { textureUrl: url, data: blob };
  67807. try {
  67808. // Put the blob into the dabase
  67809. var addRequest = transaction.objectStore("textures").put(newTexture);
  67810. addRequest.onsuccess = function (event) {
  67811. };
  67812. addRequest.onerror = function (event) {
  67813. generateBlobUrl();
  67814. };
  67815. }
  67816. catch (ex) {
  67817. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67818. if (ex.code === 25) {
  67819. Database.IsUASupportingBlobStorage = false;
  67820. }
  67821. image.src = url;
  67822. }
  67823. }
  67824. else {
  67825. image.src = url;
  67826. }
  67827. }, false);
  67828. xhr.addEventListener("error", function (event) {
  67829. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67830. image.src = url;
  67831. }, false);
  67832. xhr.send();
  67833. }
  67834. else {
  67835. image.src = url;
  67836. }
  67837. }
  67838. else {
  67839. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67840. image.src = url;
  67841. }
  67842. };
  67843. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67844. var _this = this;
  67845. var updateVersion = function () {
  67846. // the version is not yet in the DB or we need to update it
  67847. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67848. };
  67849. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67850. };
  67851. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67852. var _this = this;
  67853. if (this.isSupported && this.db) {
  67854. var version;
  67855. try {
  67856. var transaction = this.db.transaction(["versions"]);
  67857. transaction.oncomplete = function (event) {
  67858. if (version) {
  67859. // If the version in the JSON file is > than the version in DB
  67860. if (_this.manifestVersionFound > version.data) {
  67861. _this.mustUpdateRessources = true;
  67862. updateInDBCallback();
  67863. }
  67864. else {
  67865. callback(version.data);
  67866. }
  67867. }
  67868. // version was not found in DB
  67869. else {
  67870. _this.mustUpdateRessources = true;
  67871. updateInDBCallback();
  67872. }
  67873. };
  67874. transaction.onabort = function (event) {
  67875. callback(-1);
  67876. };
  67877. var getRequest = transaction.objectStore("versions").get(url);
  67878. getRequest.onsuccess = function (event) {
  67879. version = (event.target).result;
  67880. };
  67881. getRequest.onerror = function (event) {
  67882. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67883. callback(-1);
  67884. };
  67885. }
  67886. catch (ex) {
  67887. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67888. callback(-1);
  67889. }
  67890. }
  67891. else {
  67892. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67893. callback(-1);
  67894. }
  67895. };
  67896. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67897. var _this = this;
  67898. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67899. try {
  67900. // Open a transaction to the database
  67901. var transaction = this.db.transaction(["versions"], "readwrite");
  67902. // the transaction could abort because of a QuotaExceededError error
  67903. transaction.onabort = function (event) {
  67904. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67905. var error = event.srcElement['error'];
  67906. if (error && error.name === "QuotaExceededError") {
  67907. _this.hasReachedQuota = true;
  67908. }
  67909. }
  67910. catch (ex) { }
  67911. callback(-1);
  67912. };
  67913. transaction.oncomplete = function (event) {
  67914. callback(_this.manifestVersionFound);
  67915. };
  67916. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67917. // Put the scene into the database
  67918. var addRequest = transaction.objectStore("versions").put(newVersion);
  67919. addRequest.onsuccess = function (event) {
  67920. };
  67921. addRequest.onerror = function (event) {
  67922. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67923. };
  67924. }
  67925. catch (ex) {
  67926. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67927. callback(-1);
  67928. }
  67929. }
  67930. else {
  67931. callback(-1);
  67932. }
  67933. };
  67934. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67935. var _this = this;
  67936. var completeUrl = Database.ReturnFullUrlLocation(url);
  67937. var saveAndLoadFile = function () {
  67938. // the scene is not yet in the DB, let's try to save it
  67939. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67940. };
  67941. this._checkVersionFromDB(completeUrl, function (version) {
  67942. if (version !== -1) {
  67943. if (!_this.mustUpdateRessources) {
  67944. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67945. }
  67946. else {
  67947. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67948. }
  67949. }
  67950. else {
  67951. if (errorCallback) {
  67952. errorCallback();
  67953. }
  67954. }
  67955. });
  67956. };
  67957. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67958. if (this.isSupported && this.db) {
  67959. var targetStore;
  67960. if (url.indexOf(".babylon") !== -1) {
  67961. targetStore = "scenes";
  67962. }
  67963. else {
  67964. targetStore = "textures";
  67965. }
  67966. var file;
  67967. var transaction = this.db.transaction([targetStore]);
  67968. transaction.oncomplete = function (event) {
  67969. if (file) {
  67970. callback(file.data);
  67971. }
  67972. // file was not found in DB
  67973. else {
  67974. notInDBCallback();
  67975. }
  67976. };
  67977. transaction.onabort = function (event) {
  67978. notInDBCallback();
  67979. };
  67980. var getRequest = transaction.objectStore(targetStore).get(url);
  67981. getRequest.onsuccess = function (event) {
  67982. file = (event.target).result;
  67983. };
  67984. getRequest.onerror = function (event) {
  67985. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67986. notInDBCallback();
  67987. };
  67988. }
  67989. else {
  67990. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67991. callback();
  67992. }
  67993. };
  67994. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67995. var _this = this;
  67996. if (this.isSupported) {
  67997. var targetStore;
  67998. if (url.indexOf(".babylon") !== -1) {
  67999. targetStore = "scenes";
  68000. }
  68001. else {
  68002. targetStore = "textures";
  68003. }
  68004. // Create XHR
  68005. var xhr = new XMLHttpRequest();
  68006. var fileData;
  68007. xhr.open("GET", url, true);
  68008. if (useArrayBuffer) {
  68009. xhr.responseType = "arraybuffer";
  68010. }
  68011. if (progressCallback) {
  68012. xhr.onprogress = progressCallback;
  68013. }
  68014. xhr.addEventListener("load", function () {
  68015. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68016. // Blob as response (XHR2)
  68017. //fileData = xhr.responseText;
  68018. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68019. if (!_this.hasReachedQuota && _this.db) {
  68020. // Open a transaction to the database
  68021. var transaction = _this.db.transaction([targetStore], "readwrite");
  68022. // the transaction could abort because of a QuotaExceededError error
  68023. transaction.onabort = function (event) {
  68024. try {
  68025. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68026. var error = event.srcElement['error'];
  68027. if (error && error.name === "QuotaExceededError") {
  68028. _this.hasReachedQuota = true;
  68029. }
  68030. }
  68031. catch (ex) { }
  68032. callback(fileData);
  68033. };
  68034. transaction.oncomplete = function (event) {
  68035. callback(fileData);
  68036. };
  68037. var newFile;
  68038. if (targetStore === "scenes") {
  68039. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68040. }
  68041. else {
  68042. newFile = { textureUrl: url, data: fileData };
  68043. }
  68044. try {
  68045. // Put the scene into the database
  68046. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68047. addRequest.onsuccess = function (event) {
  68048. };
  68049. addRequest.onerror = function (event) {
  68050. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68051. };
  68052. }
  68053. catch (ex) {
  68054. callback(fileData);
  68055. }
  68056. }
  68057. else {
  68058. callback(fileData);
  68059. }
  68060. }
  68061. else {
  68062. callback();
  68063. }
  68064. }, false);
  68065. xhr.addEventListener("error", function (event) {
  68066. BABYLON.Tools.Error("error on XHR request.");
  68067. callback();
  68068. }, false);
  68069. xhr.send();
  68070. }
  68071. else {
  68072. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68073. callback();
  68074. }
  68075. };
  68076. Database.IsUASupportingBlobStorage = true;
  68077. Database.IDBStorageEnabled = true;
  68078. Database.parseURL = function (url) {
  68079. var a = document.createElement('a');
  68080. a.href = url;
  68081. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68082. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68083. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68084. return absLocation;
  68085. };
  68086. Database.ReturnFullUrlLocation = function (url) {
  68087. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68088. return (Database.parseURL(window.location.href) + url);
  68089. }
  68090. else {
  68091. return url;
  68092. }
  68093. };
  68094. return Database;
  68095. }());
  68096. BABYLON.Database = Database;
  68097. })(BABYLON || (BABYLON = {}));
  68098. //# sourceMappingURL=babylon.database.js.map
  68099. var BABYLON;
  68100. (function (BABYLON) {
  68101. var FresnelParameters = /** @class */ (function () {
  68102. function FresnelParameters() {
  68103. this._isEnabled = true;
  68104. this.leftColor = BABYLON.Color3.White();
  68105. this.rightColor = BABYLON.Color3.Black();
  68106. this.bias = 0;
  68107. this.power = 1;
  68108. }
  68109. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68110. get: function () {
  68111. return this._isEnabled;
  68112. },
  68113. set: function (value) {
  68114. if (this._isEnabled === value) {
  68115. return;
  68116. }
  68117. this._isEnabled = value;
  68118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68119. },
  68120. enumerable: true,
  68121. configurable: true
  68122. });
  68123. FresnelParameters.prototype.clone = function () {
  68124. var newFresnelParameters = new FresnelParameters();
  68125. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68126. return newFresnelParameters;
  68127. };
  68128. FresnelParameters.prototype.serialize = function () {
  68129. var serializationObject = {};
  68130. serializationObject.isEnabled = this.isEnabled;
  68131. serializationObject.leftColor = this.leftColor.asArray();
  68132. serializationObject.rightColor = this.rightColor.asArray();
  68133. serializationObject.bias = this.bias;
  68134. serializationObject.power = this.power;
  68135. return serializationObject;
  68136. };
  68137. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68138. var fresnelParameters = new FresnelParameters();
  68139. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68140. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68141. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68142. fresnelParameters.bias = parsedFresnelParameters.bias;
  68143. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68144. return fresnelParameters;
  68145. };
  68146. return FresnelParameters;
  68147. }());
  68148. BABYLON.FresnelParameters = FresnelParameters;
  68149. })(BABYLON || (BABYLON = {}));
  68150. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68151. var BABYLON;
  68152. (function (BABYLON) {
  68153. var MultiMaterial = /** @class */ (function (_super) {
  68154. __extends(MultiMaterial, _super);
  68155. function MultiMaterial(name, scene) {
  68156. var _this = _super.call(this, name, scene, true) || this;
  68157. scene.multiMaterials.push(_this);
  68158. _this.subMaterials = new Array();
  68159. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68160. return _this;
  68161. }
  68162. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68163. get: function () {
  68164. return this._subMaterials;
  68165. },
  68166. set: function (value) {
  68167. this._subMaterials = value;
  68168. this._hookArray(value);
  68169. },
  68170. enumerable: true,
  68171. configurable: true
  68172. });
  68173. MultiMaterial.prototype._hookArray = function (array) {
  68174. var _this = this;
  68175. var oldPush = array.push;
  68176. array.push = function () {
  68177. var items = [];
  68178. for (var _i = 0; _i < arguments.length; _i++) {
  68179. items[_i] = arguments[_i];
  68180. }
  68181. var result = oldPush.apply(array, items);
  68182. _this._markAllSubMeshesAsTexturesDirty();
  68183. return result;
  68184. };
  68185. var oldSplice = array.splice;
  68186. array.splice = function (index, deleteCount) {
  68187. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68188. _this._markAllSubMeshesAsTexturesDirty();
  68189. return deleted;
  68190. };
  68191. };
  68192. // Properties
  68193. MultiMaterial.prototype.getSubMaterial = function (index) {
  68194. if (index < 0 || index >= this.subMaterials.length) {
  68195. return this.getScene().defaultMaterial;
  68196. }
  68197. return this.subMaterials[index];
  68198. };
  68199. MultiMaterial.prototype.getActiveTextures = function () {
  68200. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68201. if (subMaterial) {
  68202. return subMaterial.getActiveTextures();
  68203. }
  68204. else {
  68205. return [];
  68206. }
  68207. }));
  68208. var _a;
  68209. };
  68210. // Methods
  68211. MultiMaterial.prototype.getClassName = function () {
  68212. return "MultiMaterial";
  68213. };
  68214. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68215. for (var index = 0; index < this.subMaterials.length; index++) {
  68216. var subMaterial = this.subMaterials[index];
  68217. if (subMaterial) {
  68218. if (subMaterial.storeEffectOnSubMeshes) {
  68219. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68220. return false;
  68221. }
  68222. continue;
  68223. }
  68224. if (!subMaterial.isReady(mesh)) {
  68225. return false;
  68226. }
  68227. }
  68228. }
  68229. return true;
  68230. };
  68231. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68232. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68233. for (var index = 0; index < this.subMaterials.length; index++) {
  68234. var subMaterial = null;
  68235. var current = this.subMaterials[index];
  68236. if (cloneChildren && current) {
  68237. subMaterial = current.clone(name + "-" + current.name);
  68238. }
  68239. else {
  68240. subMaterial = this.subMaterials[index];
  68241. }
  68242. newMultiMaterial.subMaterials.push(subMaterial);
  68243. }
  68244. return newMultiMaterial;
  68245. };
  68246. MultiMaterial.prototype.serialize = function () {
  68247. var serializationObject = {};
  68248. serializationObject.name = this.name;
  68249. serializationObject.id = this.id;
  68250. if (BABYLON.Tags) {
  68251. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68252. }
  68253. serializationObject.materials = [];
  68254. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68255. var subMat = this.subMaterials[matIndex];
  68256. if (subMat) {
  68257. serializationObject.materials.push(subMat.id);
  68258. }
  68259. else {
  68260. serializationObject.materials.push(null);
  68261. }
  68262. }
  68263. return serializationObject;
  68264. };
  68265. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68266. var scene = this.getScene();
  68267. if (!scene) {
  68268. return;
  68269. }
  68270. var index = scene.multiMaterials.indexOf(this);
  68271. if (index >= 0) {
  68272. scene.multiMaterials.splice(index, 1);
  68273. }
  68274. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68275. };
  68276. return MultiMaterial;
  68277. }(BABYLON.Material));
  68278. BABYLON.MultiMaterial = MultiMaterial;
  68279. })(BABYLON || (BABYLON = {}));
  68280. //# sourceMappingURL=babylon.multiMaterial.js.map
  68281. var BABYLON;
  68282. (function (BABYLON) {
  68283. var FreeCameraTouchInput = /** @class */ (function () {
  68284. function FreeCameraTouchInput() {
  68285. this._offsetX = null;
  68286. this._offsetY = null;
  68287. this._pointerPressed = new Array();
  68288. this.touchAngularSensibility = 200000.0;
  68289. this.touchMoveSensibility = 250.0;
  68290. }
  68291. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68292. var _this = this;
  68293. var previousPosition = null;
  68294. if (this._pointerInput === undefined) {
  68295. this._onLostFocus = function (evt) {
  68296. _this._offsetX = null;
  68297. _this._offsetY = null;
  68298. };
  68299. this._pointerInput = function (p, s) {
  68300. var evt = p.event;
  68301. if (evt.pointerType === "mouse") {
  68302. return;
  68303. }
  68304. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68305. if (!noPreventDefault) {
  68306. evt.preventDefault();
  68307. }
  68308. _this._pointerPressed.push(evt.pointerId);
  68309. if (_this._pointerPressed.length !== 1) {
  68310. return;
  68311. }
  68312. previousPosition = {
  68313. x: evt.clientX,
  68314. y: evt.clientY
  68315. };
  68316. }
  68317. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68318. if (!noPreventDefault) {
  68319. evt.preventDefault();
  68320. }
  68321. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68322. if (index === -1) {
  68323. return;
  68324. }
  68325. _this._pointerPressed.splice(index, 1);
  68326. if (index != 0) {
  68327. return;
  68328. }
  68329. previousPosition = null;
  68330. _this._offsetX = null;
  68331. _this._offsetY = null;
  68332. }
  68333. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68334. if (!noPreventDefault) {
  68335. evt.preventDefault();
  68336. }
  68337. if (!previousPosition) {
  68338. return;
  68339. }
  68340. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68341. if (index != 0) {
  68342. return;
  68343. }
  68344. _this._offsetX = evt.clientX - previousPosition.x;
  68345. _this._offsetY = -(evt.clientY - previousPosition.y);
  68346. }
  68347. };
  68348. }
  68349. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68350. if (this._onLostFocus) {
  68351. element.addEventListener("blur", this._onLostFocus);
  68352. }
  68353. };
  68354. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68355. if (this._pointerInput && element) {
  68356. if (this._observer) {
  68357. this.camera.getScene().onPointerObservable.remove(this._observer);
  68358. this._observer = null;
  68359. }
  68360. if (this._onLostFocus) {
  68361. element.removeEventListener("blur", this._onLostFocus);
  68362. this._onLostFocus = null;
  68363. }
  68364. this._pointerPressed = [];
  68365. this._offsetX = null;
  68366. this._offsetY = null;
  68367. }
  68368. };
  68369. FreeCameraTouchInput.prototype.checkInputs = function () {
  68370. if (this._offsetX && this._offsetY) {
  68371. var camera = this.camera;
  68372. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68373. if (this._pointerPressed.length > 1) {
  68374. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68375. }
  68376. else {
  68377. var speed = camera._computeLocalCameraSpeed();
  68378. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68379. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68380. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68381. }
  68382. }
  68383. };
  68384. FreeCameraTouchInput.prototype.getClassName = function () {
  68385. return "FreeCameraTouchInput";
  68386. };
  68387. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68388. return "touch";
  68389. };
  68390. __decorate([
  68391. BABYLON.serialize()
  68392. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68393. __decorate([
  68394. BABYLON.serialize()
  68395. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68396. return FreeCameraTouchInput;
  68397. }());
  68398. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68399. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68400. })(BABYLON || (BABYLON = {}));
  68401. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68402. var BABYLON;
  68403. (function (BABYLON) {
  68404. // We're mainly based on the logic defined into the FreeCamera code
  68405. var TouchCamera = /** @class */ (function (_super) {
  68406. __extends(TouchCamera, _super);
  68407. //-- end properties for backward compatibility for inputs
  68408. function TouchCamera(name, position, scene) {
  68409. var _this = _super.call(this, name, position, scene) || this;
  68410. _this.inputs.addTouch();
  68411. _this._setupInputs();
  68412. return _this;
  68413. }
  68414. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68415. //-- Begin properties for backward compatibility for inputs
  68416. get: function () {
  68417. var touch = this.inputs.attached["touch"];
  68418. if (touch)
  68419. return touch.touchAngularSensibility;
  68420. return 0;
  68421. },
  68422. set: function (value) {
  68423. var touch = this.inputs.attached["touch"];
  68424. if (touch)
  68425. touch.touchAngularSensibility = value;
  68426. },
  68427. enumerable: true,
  68428. configurable: true
  68429. });
  68430. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68431. get: function () {
  68432. var touch = this.inputs.attached["touch"];
  68433. if (touch)
  68434. return touch.touchMoveSensibility;
  68435. return 0;
  68436. },
  68437. set: function (value) {
  68438. var touch = this.inputs.attached["touch"];
  68439. if (touch)
  68440. touch.touchMoveSensibility = value;
  68441. },
  68442. enumerable: true,
  68443. configurable: true
  68444. });
  68445. TouchCamera.prototype.getClassName = function () {
  68446. return "TouchCamera";
  68447. };
  68448. TouchCamera.prototype._setupInputs = function () {
  68449. var mouse = this.inputs.attached["mouse"];
  68450. if (mouse) {
  68451. mouse.touchEnabled = false;
  68452. }
  68453. };
  68454. return TouchCamera;
  68455. }(BABYLON.FreeCamera));
  68456. BABYLON.TouchCamera = TouchCamera;
  68457. })(BABYLON || (BABYLON = {}));
  68458. //# sourceMappingURL=babylon.touchCamera.js.map
  68459. var BABYLON;
  68460. (function (BABYLON) {
  68461. var ProceduralTexture = /** @class */ (function (_super) {
  68462. __extends(ProceduralTexture, _super);
  68463. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68464. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68466. if (isCube === void 0) { isCube = false; }
  68467. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68468. _this.isCube = isCube;
  68469. _this.isEnabled = true;
  68470. _this._currentRefreshId = -1;
  68471. _this._refreshRate = 1;
  68472. _this._vertexBuffers = {};
  68473. _this._uniforms = new Array();
  68474. _this._samplers = new Array();
  68475. _this._textures = {};
  68476. _this._floats = {};
  68477. _this._floatsArrays = {};
  68478. _this._colors3 = {};
  68479. _this._colors4 = {};
  68480. _this._vectors2 = {};
  68481. _this._vectors3 = {};
  68482. _this._matrices = {};
  68483. _this._fallbackTextureUsed = false;
  68484. scene.proceduralTextures.push(_this);
  68485. _this._engine = scene.getEngine();
  68486. _this.name = name;
  68487. _this.isRenderTarget = true;
  68488. _this._size = size;
  68489. _this._generateMipMaps = generateMipMaps;
  68490. _this.setFragment(fragment);
  68491. _this._fallbackTexture = fallbackTexture;
  68492. if (isCube) {
  68493. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68494. _this.setFloat("face", 0);
  68495. }
  68496. else {
  68497. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68498. }
  68499. // VBO
  68500. var vertices = [];
  68501. vertices.push(1, 1);
  68502. vertices.push(-1, 1);
  68503. vertices.push(-1, -1);
  68504. vertices.push(1, -1);
  68505. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68506. _this._createIndexBuffer();
  68507. return _this;
  68508. }
  68509. ProceduralTexture.prototype._createIndexBuffer = function () {
  68510. var engine = this._engine;
  68511. // Indices
  68512. var indices = [];
  68513. indices.push(0);
  68514. indices.push(1);
  68515. indices.push(2);
  68516. indices.push(0);
  68517. indices.push(2);
  68518. indices.push(3);
  68519. this._indexBuffer = engine.createIndexBuffer(indices);
  68520. };
  68521. ProceduralTexture.prototype._rebuild = function () {
  68522. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68523. if (vb) {
  68524. vb._rebuild();
  68525. }
  68526. this._createIndexBuffer();
  68527. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68528. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68529. }
  68530. };
  68531. ProceduralTexture.prototype.reset = function () {
  68532. if (this._effect === undefined) {
  68533. return;
  68534. }
  68535. var engine = this._engine;
  68536. engine._releaseEffect(this._effect);
  68537. };
  68538. ProceduralTexture.prototype.isReady = function () {
  68539. var _this = this;
  68540. var engine = this._engine;
  68541. var shaders;
  68542. if (!this._fragment) {
  68543. return false;
  68544. }
  68545. if (this._fallbackTextureUsed) {
  68546. return true;
  68547. }
  68548. if (this._fragment.fragmentElement !== undefined) {
  68549. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68550. }
  68551. else {
  68552. shaders = { vertex: "procedural", fragment: this._fragment };
  68553. }
  68554. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68555. _this.releaseInternalTexture();
  68556. if (_this._fallbackTexture) {
  68557. _this._texture = _this._fallbackTexture._texture;
  68558. if (_this._texture) {
  68559. _this._texture.incrementReferences();
  68560. }
  68561. }
  68562. _this._fallbackTextureUsed = true;
  68563. });
  68564. return this._effect.isReady();
  68565. };
  68566. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68567. this._currentRefreshId = -1;
  68568. };
  68569. ProceduralTexture.prototype.setFragment = function (fragment) {
  68570. this._fragment = fragment;
  68571. };
  68572. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68573. get: function () {
  68574. return this._refreshRate;
  68575. },
  68576. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68577. set: function (value) {
  68578. this._refreshRate = value;
  68579. this.resetRefreshCounter();
  68580. },
  68581. enumerable: true,
  68582. configurable: true
  68583. });
  68584. ProceduralTexture.prototype._shouldRender = function () {
  68585. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68586. return false;
  68587. }
  68588. if (this._fallbackTextureUsed) {
  68589. return false;
  68590. }
  68591. if (this._currentRefreshId === -1) { // At least render once
  68592. this._currentRefreshId = 1;
  68593. return true;
  68594. }
  68595. if (this.refreshRate === this._currentRefreshId) {
  68596. this._currentRefreshId = 1;
  68597. return true;
  68598. }
  68599. this._currentRefreshId++;
  68600. return false;
  68601. };
  68602. ProceduralTexture.prototype.getRenderSize = function () {
  68603. return this._size;
  68604. };
  68605. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68606. if (this._fallbackTextureUsed) {
  68607. return;
  68608. }
  68609. this.releaseInternalTexture();
  68610. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68611. };
  68612. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68613. if (this._uniforms.indexOf(uniformName) === -1) {
  68614. this._uniforms.push(uniformName);
  68615. }
  68616. };
  68617. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68618. if (this._samplers.indexOf(name) === -1) {
  68619. this._samplers.push(name);
  68620. }
  68621. this._textures[name] = texture;
  68622. return this;
  68623. };
  68624. ProceduralTexture.prototype.setFloat = function (name, value) {
  68625. this._checkUniform(name);
  68626. this._floats[name] = value;
  68627. return this;
  68628. };
  68629. ProceduralTexture.prototype.setFloats = function (name, value) {
  68630. this._checkUniform(name);
  68631. this._floatsArrays[name] = value;
  68632. return this;
  68633. };
  68634. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68635. this._checkUniform(name);
  68636. this._colors3[name] = value;
  68637. return this;
  68638. };
  68639. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68640. this._checkUniform(name);
  68641. this._colors4[name] = value;
  68642. return this;
  68643. };
  68644. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68645. this._checkUniform(name);
  68646. this._vectors2[name] = value;
  68647. return this;
  68648. };
  68649. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68650. this._checkUniform(name);
  68651. this._vectors3[name] = value;
  68652. return this;
  68653. };
  68654. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68655. this._checkUniform(name);
  68656. this._matrices[name] = value;
  68657. return this;
  68658. };
  68659. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68660. var scene = this.getScene();
  68661. if (!scene) {
  68662. return;
  68663. }
  68664. var engine = this._engine;
  68665. // Render
  68666. engine.enableEffect(this._effect);
  68667. engine.setState(false);
  68668. // Texture
  68669. for (var name in this._textures) {
  68670. this._effect.setTexture(name, this._textures[name]);
  68671. }
  68672. // Float
  68673. for (name in this._floats) {
  68674. this._effect.setFloat(name, this._floats[name]);
  68675. }
  68676. // Floats
  68677. for (name in this._floatsArrays) {
  68678. this._effect.setArray(name, this._floatsArrays[name]);
  68679. }
  68680. // Color3
  68681. for (name in this._colors3) {
  68682. this._effect.setColor3(name, this._colors3[name]);
  68683. }
  68684. // Color4
  68685. for (name in this._colors4) {
  68686. var color = this._colors4[name];
  68687. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68688. }
  68689. // Vector2
  68690. for (name in this._vectors2) {
  68691. this._effect.setVector2(name, this._vectors2[name]);
  68692. }
  68693. // Vector3
  68694. for (name in this._vectors3) {
  68695. this._effect.setVector3(name, this._vectors3[name]);
  68696. }
  68697. // Matrix
  68698. for (name in this._matrices) {
  68699. this._effect.setMatrix(name, this._matrices[name]);
  68700. }
  68701. if (!this._texture) {
  68702. return;
  68703. }
  68704. if (this.isCube) {
  68705. for (var face = 0; face < 6; face++) {
  68706. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68707. // VBOs
  68708. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68709. this._effect.setFloat("face", face);
  68710. // Clear
  68711. engine.clear(scene.clearColor, true, true, true);
  68712. // Draw order
  68713. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68714. // Mipmaps
  68715. if (face === 5) {
  68716. engine.generateMipMapsForCubemap(this._texture);
  68717. }
  68718. }
  68719. }
  68720. else {
  68721. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68722. // VBOs
  68723. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68724. // Clear
  68725. engine.clear(scene.clearColor, true, true, true);
  68726. // Draw order
  68727. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68728. }
  68729. // Unbind
  68730. engine.unBindFramebuffer(this._texture, this.isCube);
  68731. if (this.onGenerated) {
  68732. this.onGenerated();
  68733. }
  68734. };
  68735. ProceduralTexture.prototype.clone = function () {
  68736. var textureSize = this.getSize();
  68737. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68738. // Base texture
  68739. newTexture.hasAlpha = this.hasAlpha;
  68740. newTexture.level = this.level;
  68741. // RenderTarget Texture
  68742. newTexture.coordinatesMode = this.coordinatesMode;
  68743. return newTexture;
  68744. };
  68745. ProceduralTexture.prototype.dispose = function () {
  68746. var scene = this.getScene();
  68747. if (!scene) {
  68748. return;
  68749. }
  68750. var index = scene.proceduralTextures.indexOf(this);
  68751. if (index >= 0) {
  68752. scene.proceduralTextures.splice(index, 1);
  68753. }
  68754. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68755. if (vertexBuffer) {
  68756. vertexBuffer.dispose();
  68757. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68758. }
  68759. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68760. this._indexBuffer = null;
  68761. }
  68762. _super.prototype.dispose.call(this);
  68763. };
  68764. return ProceduralTexture;
  68765. }(BABYLON.Texture));
  68766. BABYLON.ProceduralTexture = ProceduralTexture;
  68767. })(BABYLON || (BABYLON = {}));
  68768. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68769. var BABYLON;
  68770. (function (BABYLON) {
  68771. var CustomProceduralTexture = /** @class */ (function (_super) {
  68772. __extends(CustomProceduralTexture, _super);
  68773. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68774. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68775. _this._animate = true;
  68776. _this._time = 0;
  68777. _this._texturePath = texturePath;
  68778. //Try to load json
  68779. _this.loadJson(texturePath);
  68780. _this.refreshRate = 1;
  68781. return _this;
  68782. }
  68783. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68784. var _this = this;
  68785. var noConfigFile = function () {
  68786. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68787. try {
  68788. _this.setFragment(_this._texturePath);
  68789. }
  68790. catch (ex) {
  68791. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68792. }
  68793. };
  68794. var configFileUrl = jsonUrl + "/config.json";
  68795. var xhr = new XMLHttpRequest();
  68796. xhr.open("GET", configFileUrl, true);
  68797. xhr.addEventListener("load", function () {
  68798. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68799. try {
  68800. _this._config = JSON.parse(xhr.response);
  68801. _this.updateShaderUniforms();
  68802. _this.updateTextures();
  68803. _this.setFragment(_this._texturePath + "/custom");
  68804. _this._animate = _this._config.animate;
  68805. _this.refreshRate = _this._config.refreshrate;
  68806. }
  68807. catch (ex) {
  68808. noConfigFile();
  68809. }
  68810. }
  68811. else {
  68812. noConfigFile();
  68813. }
  68814. }, false);
  68815. xhr.addEventListener("error", function () {
  68816. noConfigFile();
  68817. }, false);
  68818. try {
  68819. xhr.send();
  68820. }
  68821. catch (ex) {
  68822. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68823. }
  68824. };
  68825. CustomProceduralTexture.prototype.isReady = function () {
  68826. if (!_super.prototype.isReady.call(this)) {
  68827. return false;
  68828. }
  68829. for (var name in this._textures) {
  68830. var texture = this._textures[name];
  68831. if (!texture.isReady()) {
  68832. return false;
  68833. }
  68834. }
  68835. return true;
  68836. };
  68837. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68838. var scene = this.getScene();
  68839. if (this._animate && scene) {
  68840. this._time += scene.getAnimationRatio() * 0.03;
  68841. this.updateShaderUniforms();
  68842. }
  68843. _super.prototype.render.call(this, useCameraPostProcess);
  68844. };
  68845. CustomProceduralTexture.prototype.updateTextures = function () {
  68846. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68847. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68848. }
  68849. };
  68850. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68851. if (this._config) {
  68852. for (var j = 0; j < this._config.uniforms.length; j++) {
  68853. var uniform = this._config.uniforms[j];
  68854. switch (uniform.type) {
  68855. case "float":
  68856. this.setFloat(uniform.name, uniform.value);
  68857. break;
  68858. case "color3":
  68859. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68860. break;
  68861. case "color4":
  68862. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68863. break;
  68864. case "vector2":
  68865. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68866. break;
  68867. case "vector3":
  68868. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68869. break;
  68870. }
  68871. }
  68872. }
  68873. this.setFloat("time", this._time);
  68874. };
  68875. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68876. get: function () {
  68877. return this._animate;
  68878. },
  68879. set: function (value) {
  68880. this._animate = value;
  68881. },
  68882. enumerable: true,
  68883. configurable: true
  68884. });
  68885. return CustomProceduralTexture;
  68886. }(BABYLON.ProceduralTexture));
  68887. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68888. })(BABYLON || (BABYLON = {}));
  68889. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68890. var BABYLON;
  68891. (function (BABYLON) {
  68892. var FreeCameraGamepadInput = /** @class */ (function () {
  68893. function FreeCameraGamepadInput() {
  68894. this.gamepadAngularSensibility = 200;
  68895. this.gamepadMoveSensibility = 40;
  68896. // private members
  68897. this._cameraTransform = BABYLON.Matrix.Identity();
  68898. this._deltaTransform = BABYLON.Vector3.Zero();
  68899. this._vector3 = BABYLON.Vector3.Zero();
  68900. this._vector2 = BABYLON.Vector2.Zero();
  68901. }
  68902. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68903. var _this = this;
  68904. var manager = this.camera.getScene().gamepadManager;
  68905. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68906. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68907. // prioritize XBOX gamepads.
  68908. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68909. _this.gamepad = gamepad;
  68910. }
  68911. }
  68912. });
  68913. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68914. if (_this.gamepad === gamepad) {
  68915. _this.gamepad = null;
  68916. }
  68917. });
  68918. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68919. };
  68920. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68921. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68922. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68923. this.gamepad = null;
  68924. };
  68925. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68926. if (this.gamepad && this.gamepad.leftStick) {
  68927. var camera = this.camera;
  68928. var LSValues = this.gamepad.leftStick;
  68929. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68930. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68931. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68932. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68933. var RSValues = this.gamepad.rightStick;
  68934. if (RSValues) {
  68935. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68936. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68937. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68938. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68939. }
  68940. else {
  68941. RSValues = { x: 0, y: 0 };
  68942. }
  68943. if (!camera.rotationQuaternion) {
  68944. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68945. }
  68946. else {
  68947. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68948. }
  68949. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68950. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68951. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68952. camera.cameraDirection.addInPlace(this._deltaTransform);
  68953. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68954. camera.cameraRotation.addInPlace(this._vector2);
  68955. }
  68956. };
  68957. FreeCameraGamepadInput.prototype.getClassName = function () {
  68958. return "FreeCameraGamepadInput";
  68959. };
  68960. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68961. return "gamepad";
  68962. };
  68963. __decorate([
  68964. BABYLON.serialize()
  68965. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68966. __decorate([
  68967. BABYLON.serialize()
  68968. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68969. return FreeCameraGamepadInput;
  68970. }());
  68971. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68972. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68973. })(BABYLON || (BABYLON = {}));
  68974. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68975. var BABYLON;
  68976. (function (BABYLON) {
  68977. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68978. function ArcRotateCameraGamepadInput() {
  68979. this.gamepadRotationSensibility = 80;
  68980. this.gamepadMoveSensibility = 40;
  68981. }
  68982. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68983. var _this = this;
  68984. var manager = this.camera.getScene().gamepadManager;
  68985. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68986. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68987. // prioritize XBOX gamepads.
  68988. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68989. _this.gamepad = gamepad;
  68990. }
  68991. }
  68992. });
  68993. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68994. if (_this.gamepad === gamepad) {
  68995. _this.gamepad = null;
  68996. }
  68997. });
  68998. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68999. };
  69000. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69001. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69002. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69003. this.gamepad = null;
  69004. };
  69005. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69006. if (this.gamepad) {
  69007. var camera = this.camera;
  69008. var RSValues = this.gamepad.rightStick;
  69009. if (RSValues) {
  69010. if (RSValues.x != 0) {
  69011. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69012. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69013. camera.inertialAlphaOffset += normalizedRX;
  69014. }
  69015. }
  69016. if (RSValues.y != 0) {
  69017. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69018. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69019. camera.inertialBetaOffset += normalizedRY;
  69020. }
  69021. }
  69022. }
  69023. var LSValues = this.gamepad.leftStick;
  69024. if (LSValues && LSValues.y != 0) {
  69025. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69026. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69027. this.camera.inertialRadiusOffset -= normalizedLY;
  69028. }
  69029. }
  69030. }
  69031. };
  69032. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69033. return "ArcRotateCameraGamepadInput";
  69034. };
  69035. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69036. return "gamepad";
  69037. };
  69038. __decorate([
  69039. BABYLON.serialize()
  69040. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69041. __decorate([
  69042. BABYLON.serialize()
  69043. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69044. return ArcRotateCameraGamepadInput;
  69045. }());
  69046. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69047. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69048. })(BABYLON || (BABYLON = {}));
  69049. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69050. var BABYLON;
  69051. (function (BABYLON) {
  69052. var GamepadManager = /** @class */ (function () {
  69053. function GamepadManager(_scene) {
  69054. var _this = this;
  69055. this._scene = _scene;
  69056. this._babylonGamepads = [];
  69057. this._oneGamepadConnected = false;
  69058. this._isMonitoring = false;
  69059. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69060. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69061. this._gamepadEventSupported = false;
  69062. }
  69063. else {
  69064. this._gamepadEventSupported = 'GamepadEvent' in window;
  69065. this._gamepadSupport = (navigator.getGamepads ||
  69066. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69067. }
  69068. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69069. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69070. for (var i in _this._babylonGamepads) {
  69071. var gamepad = _this._babylonGamepads[i];
  69072. if (gamepad && gamepad._isConnected) {
  69073. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69074. }
  69075. }
  69076. });
  69077. this._onGamepadConnectedEvent = function (evt) {
  69078. var gamepad = evt.gamepad;
  69079. if (gamepad.index in _this._babylonGamepads) {
  69080. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69081. return;
  69082. }
  69083. }
  69084. var newGamepad;
  69085. if (_this._babylonGamepads[gamepad.index]) {
  69086. newGamepad = _this._babylonGamepads[gamepad.index];
  69087. newGamepad.browserGamepad = gamepad;
  69088. newGamepad._isConnected = true;
  69089. }
  69090. else {
  69091. newGamepad = _this._addNewGamepad(gamepad);
  69092. }
  69093. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69094. _this._startMonitoringGamepads();
  69095. };
  69096. this._onGamepadDisconnectedEvent = function (evt) {
  69097. var gamepad = evt.gamepad;
  69098. // Remove the gamepad from the list of gamepads to monitor.
  69099. for (var i in _this._babylonGamepads) {
  69100. if (_this._babylonGamepads[i].index === gamepad.index) {
  69101. var disconnectedGamepad = _this._babylonGamepads[i];
  69102. disconnectedGamepad._isConnected = false;
  69103. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69104. break;
  69105. }
  69106. }
  69107. };
  69108. if (this._gamepadSupport) {
  69109. //first add already-connected gamepads
  69110. this._updateGamepadObjects();
  69111. if (this._babylonGamepads.length) {
  69112. this._startMonitoringGamepads();
  69113. }
  69114. // Checking if the gamepad connected event is supported (like in Firefox)
  69115. if (this._gamepadEventSupported) {
  69116. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69117. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69118. }
  69119. else {
  69120. this._startMonitoringGamepads();
  69121. }
  69122. }
  69123. }
  69124. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69125. get: function () {
  69126. return this._babylonGamepads;
  69127. },
  69128. enumerable: true,
  69129. configurable: true
  69130. });
  69131. GamepadManager.prototype.getGamepadByType = function (type) {
  69132. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69133. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69134. var gamepad = _a[_i];
  69135. if (gamepad && gamepad.type === type) {
  69136. return gamepad;
  69137. }
  69138. }
  69139. return null;
  69140. };
  69141. GamepadManager.prototype.dispose = function () {
  69142. if (this._gamepadEventSupported) {
  69143. if (this._onGamepadConnectedEvent) {
  69144. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69145. }
  69146. if (this._onGamepadDisconnectedEvent) {
  69147. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69148. }
  69149. this._onGamepadConnectedEvent = null;
  69150. this._onGamepadDisconnectedEvent = null;
  69151. }
  69152. this._babylonGamepads.forEach(function (gamepad) {
  69153. gamepad.dispose();
  69154. });
  69155. this.onGamepadConnectedObservable.clear();
  69156. this.onGamepadDisconnectedObservable.clear();
  69157. this._oneGamepadConnected = false;
  69158. this._stopMonitoringGamepads();
  69159. this._babylonGamepads = [];
  69160. };
  69161. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69162. if (!this._oneGamepadConnected) {
  69163. this._oneGamepadConnected = true;
  69164. }
  69165. var newGamepad;
  69166. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69167. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69168. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69169. }
  69170. // if pose is supported, use the (WebVR) pose enabled controller
  69171. else if (gamepad.pose) {
  69172. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69173. }
  69174. else {
  69175. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69176. }
  69177. this._babylonGamepads[newGamepad.index] = newGamepad;
  69178. return newGamepad;
  69179. };
  69180. GamepadManager.prototype._startMonitoringGamepads = function () {
  69181. if (!this._isMonitoring) {
  69182. this._isMonitoring = true;
  69183. //back-comp
  69184. if (!this._scene) {
  69185. this._checkGamepadsStatus();
  69186. }
  69187. }
  69188. };
  69189. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69190. this._isMonitoring = false;
  69191. };
  69192. GamepadManager.prototype._checkGamepadsStatus = function () {
  69193. var _this = this;
  69194. // Hack to be compatible Chrome
  69195. this._updateGamepadObjects();
  69196. for (var i in this._babylonGamepads) {
  69197. var gamepad = this._babylonGamepads[i];
  69198. if (!gamepad || !gamepad.isConnected) {
  69199. continue;
  69200. }
  69201. gamepad.update();
  69202. }
  69203. if (this._isMonitoring && !this._scene) {
  69204. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69205. }
  69206. };
  69207. // This function is called only on Chrome, which does not properly support
  69208. // connection/disconnection events and forces you to recopy again the gamepad object
  69209. GamepadManager.prototype._updateGamepadObjects = function () {
  69210. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69211. for (var i = 0; i < gamepads.length; i++) {
  69212. var gamepad = gamepads[i];
  69213. if (gamepad) {
  69214. if (!this._babylonGamepads[gamepad.index]) {
  69215. var newGamepad = this._addNewGamepad(gamepad);
  69216. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69217. }
  69218. else {
  69219. // Forced to copy again this object for Chrome for unknown reason
  69220. this._babylonGamepads[i].browserGamepad = gamepad;
  69221. if (!this._babylonGamepads[i].isConnected) {
  69222. this._babylonGamepads[i]._isConnected = true;
  69223. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69224. }
  69225. }
  69226. }
  69227. }
  69228. };
  69229. return GamepadManager;
  69230. }());
  69231. BABYLON.GamepadManager = GamepadManager;
  69232. })(BABYLON || (BABYLON = {}));
  69233. //# sourceMappingURL=babylon.gamepadManager.js.map
  69234. var BABYLON;
  69235. (function (BABYLON) {
  69236. var StickValues = /** @class */ (function () {
  69237. function StickValues(x, y) {
  69238. this.x = x;
  69239. this.y = y;
  69240. }
  69241. return StickValues;
  69242. }());
  69243. BABYLON.StickValues = StickValues;
  69244. var Gamepad = /** @class */ (function () {
  69245. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69246. if (leftStickX === void 0) { leftStickX = 0; }
  69247. if (leftStickY === void 0) { leftStickY = 1; }
  69248. if (rightStickX === void 0) { rightStickX = 2; }
  69249. if (rightStickY === void 0) { rightStickY = 3; }
  69250. this.id = id;
  69251. this.index = index;
  69252. this.browserGamepad = browserGamepad;
  69253. this._isConnected = true;
  69254. this._invertLeftStickY = false;
  69255. this.type = Gamepad.GAMEPAD;
  69256. this._leftStickAxisX = leftStickX;
  69257. this._leftStickAxisY = leftStickY;
  69258. this._rightStickAxisX = rightStickX;
  69259. this._rightStickAxisY = rightStickY;
  69260. if (this.browserGamepad.axes.length >= 2) {
  69261. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69262. }
  69263. if (this.browserGamepad.axes.length >= 4) {
  69264. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69265. }
  69266. }
  69267. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69268. get: function () {
  69269. return this._isConnected;
  69270. },
  69271. enumerable: true,
  69272. configurable: true
  69273. });
  69274. Gamepad.prototype.onleftstickchanged = function (callback) {
  69275. this._onleftstickchanged = callback;
  69276. };
  69277. Gamepad.prototype.onrightstickchanged = function (callback) {
  69278. this._onrightstickchanged = callback;
  69279. };
  69280. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69281. get: function () {
  69282. return this._leftStick;
  69283. },
  69284. set: function (newValues) {
  69285. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69286. this._onleftstickchanged(newValues);
  69287. }
  69288. this._leftStick = newValues;
  69289. },
  69290. enumerable: true,
  69291. configurable: true
  69292. });
  69293. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69294. get: function () {
  69295. return this._rightStick;
  69296. },
  69297. set: function (newValues) {
  69298. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69299. this._onrightstickchanged(newValues);
  69300. }
  69301. this._rightStick = newValues;
  69302. },
  69303. enumerable: true,
  69304. configurable: true
  69305. });
  69306. Gamepad.prototype.update = function () {
  69307. if (this._leftStick) {
  69308. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69309. if (this._invertLeftStickY) {
  69310. this.leftStick.y *= -1;
  69311. }
  69312. }
  69313. if (this._rightStick) {
  69314. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69315. }
  69316. };
  69317. Gamepad.prototype.dispose = function () {
  69318. };
  69319. Gamepad.GAMEPAD = 0;
  69320. Gamepad.GENERIC = 1;
  69321. Gamepad.XBOX = 2;
  69322. Gamepad.POSE_ENABLED = 3;
  69323. return Gamepad;
  69324. }());
  69325. BABYLON.Gamepad = Gamepad;
  69326. var GenericPad = /** @class */ (function (_super) {
  69327. __extends(GenericPad, _super);
  69328. function GenericPad(id, index, browserGamepad) {
  69329. var _this = _super.call(this, id, index, browserGamepad) || this;
  69330. _this.onButtonDownObservable = new BABYLON.Observable();
  69331. _this.onButtonUpObservable = new BABYLON.Observable();
  69332. _this.type = Gamepad.GENERIC;
  69333. _this._buttons = new Array(browserGamepad.buttons.length);
  69334. return _this;
  69335. }
  69336. GenericPad.prototype.onbuttondown = function (callback) {
  69337. this._onbuttondown = callback;
  69338. };
  69339. GenericPad.prototype.onbuttonup = function (callback) {
  69340. this._onbuttonup = callback;
  69341. };
  69342. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69343. if (newValue !== currentValue) {
  69344. if (newValue === 1) {
  69345. if (this._onbuttondown) {
  69346. this._onbuttondown(buttonIndex);
  69347. }
  69348. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69349. }
  69350. if (newValue === 0) {
  69351. if (this._onbuttonup) {
  69352. this._onbuttonup(buttonIndex);
  69353. }
  69354. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69355. }
  69356. }
  69357. return newValue;
  69358. };
  69359. GenericPad.prototype.update = function () {
  69360. _super.prototype.update.call(this);
  69361. for (var index = 0; index < this._buttons.length; index++) {
  69362. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69363. }
  69364. };
  69365. GenericPad.prototype.dispose = function () {
  69366. _super.prototype.dispose.call(this);
  69367. this.onButtonDownObservable.clear();
  69368. this.onButtonUpObservable.clear();
  69369. };
  69370. return GenericPad;
  69371. }(Gamepad));
  69372. BABYLON.GenericPad = GenericPad;
  69373. })(BABYLON || (BABYLON = {}));
  69374. //# sourceMappingURL=babylon.gamepad.js.map
  69375. var BABYLON;
  69376. (function (BABYLON) {
  69377. var Xbox360Button;
  69378. (function (Xbox360Button) {
  69379. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69380. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69381. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69382. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69383. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69384. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69385. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69386. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69387. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69388. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69389. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69390. var Xbox360Dpad;
  69391. (function (Xbox360Dpad) {
  69392. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69393. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69394. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69395. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69396. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69397. var Xbox360Pad = /** @class */ (function (_super) {
  69398. __extends(Xbox360Pad, _super);
  69399. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69400. if (xboxOne === void 0) { xboxOne = false; }
  69401. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69402. _this._leftTrigger = 0;
  69403. _this._rightTrigger = 0;
  69404. _this.onButtonDownObservable = new BABYLON.Observable();
  69405. _this.onButtonUpObservable = new BABYLON.Observable();
  69406. _this.onPadDownObservable = new BABYLON.Observable();
  69407. _this.onPadUpObservable = new BABYLON.Observable();
  69408. _this._buttonA = 0;
  69409. _this._buttonB = 0;
  69410. _this._buttonX = 0;
  69411. _this._buttonY = 0;
  69412. _this._buttonBack = 0;
  69413. _this._buttonStart = 0;
  69414. _this._buttonLB = 0;
  69415. _this._buttonRB = 0;
  69416. _this._buttonLeftStick = 0;
  69417. _this._buttonRightStick = 0;
  69418. _this._dPadUp = 0;
  69419. _this._dPadDown = 0;
  69420. _this._dPadLeft = 0;
  69421. _this._dPadRight = 0;
  69422. _this._isXboxOnePad = false;
  69423. _this.type = BABYLON.Gamepad.XBOX;
  69424. _this._isXboxOnePad = xboxOne;
  69425. return _this;
  69426. }
  69427. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69428. this._onlefttriggerchanged = callback;
  69429. };
  69430. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69431. this._onrighttriggerchanged = callback;
  69432. };
  69433. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69434. get: function () {
  69435. return this._leftTrigger;
  69436. },
  69437. set: function (newValue) {
  69438. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69439. this._onlefttriggerchanged(newValue);
  69440. }
  69441. this._leftTrigger = newValue;
  69442. },
  69443. enumerable: true,
  69444. configurable: true
  69445. });
  69446. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69447. get: function () {
  69448. return this._rightTrigger;
  69449. },
  69450. set: function (newValue) {
  69451. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69452. this._onrighttriggerchanged(newValue);
  69453. }
  69454. this._rightTrigger = newValue;
  69455. },
  69456. enumerable: true,
  69457. configurable: true
  69458. });
  69459. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69460. this._onbuttondown = callback;
  69461. };
  69462. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69463. this._onbuttonup = callback;
  69464. };
  69465. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69466. this._ondpaddown = callback;
  69467. };
  69468. Xbox360Pad.prototype.ondpadup = function (callback) {
  69469. this._ondpadup = callback;
  69470. };
  69471. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69472. if (newValue !== currentValue) {
  69473. if (newValue === 1) {
  69474. if (this._onbuttondown) {
  69475. this._onbuttondown(buttonType);
  69476. }
  69477. this.onButtonDownObservable.notifyObservers(buttonType);
  69478. }
  69479. if (newValue === 0) {
  69480. if (this._onbuttonup) {
  69481. this._onbuttonup(buttonType);
  69482. }
  69483. this.onButtonUpObservable.notifyObservers(buttonType);
  69484. }
  69485. }
  69486. return newValue;
  69487. };
  69488. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69489. if (newValue !== currentValue) {
  69490. if (newValue === 1) {
  69491. if (this._ondpaddown) {
  69492. this._ondpaddown(buttonType);
  69493. }
  69494. this.onPadDownObservable.notifyObservers(buttonType);
  69495. }
  69496. if (newValue === 0) {
  69497. if (this._ondpadup) {
  69498. this._ondpadup(buttonType);
  69499. }
  69500. this.onPadUpObservable.notifyObservers(buttonType);
  69501. }
  69502. }
  69503. return newValue;
  69504. };
  69505. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69506. get: function () {
  69507. return this._buttonA;
  69508. },
  69509. set: function (value) {
  69510. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69511. },
  69512. enumerable: true,
  69513. configurable: true
  69514. });
  69515. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69516. get: function () {
  69517. return this._buttonB;
  69518. },
  69519. set: function (value) {
  69520. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69521. },
  69522. enumerable: true,
  69523. configurable: true
  69524. });
  69525. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69526. get: function () {
  69527. return this._buttonX;
  69528. },
  69529. set: function (value) {
  69530. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69531. },
  69532. enumerable: true,
  69533. configurable: true
  69534. });
  69535. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69536. get: function () {
  69537. return this._buttonY;
  69538. },
  69539. set: function (value) {
  69540. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69541. },
  69542. enumerable: true,
  69543. configurable: true
  69544. });
  69545. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69546. get: function () {
  69547. return this._buttonStart;
  69548. },
  69549. set: function (value) {
  69550. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69551. },
  69552. enumerable: true,
  69553. configurable: true
  69554. });
  69555. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69556. get: function () {
  69557. return this._buttonBack;
  69558. },
  69559. set: function (value) {
  69560. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69561. },
  69562. enumerable: true,
  69563. configurable: true
  69564. });
  69565. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69566. get: function () {
  69567. return this._buttonLB;
  69568. },
  69569. set: function (value) {
  69570. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69571. },
  69572. enumerable: true,
  69573. configurable: true
  69574. });
  69575. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69576. get: function () {
  69577. return this._buttonRB;
  69578. },
  69579. set: function (value) {
  69580. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69581. },
  69582. enumerable: true,
  69583. configurable: true
  69584. });
  69585. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69586. get: function () {
  69587. return this._buttonLeftStick;
  69588. },
  69589. set: function (value) {
  69590. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69591. },
  69592. enumerable: true,
  69593. configurable: true
  69594. });
  69595. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69596. get: function () {
  69597. return this._buttonRightStick;
  69598. },
  69599. set: function (value) {
  69600. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69601. },
  69602. enumerable: true,
  69603. configurable: true
  69604. });
  69605. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69606. get: function () {
  69607. return this._dPadUp;
  69608. },
  69609. set: function (value) {
  69610. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69611. },
  69612. enumerable: true,
  69613. configurable: true
  69614. });
  69615. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69616. get: function () {
  69617. return this._dPadDown;
  69618. },
  69619. set: function (value) {
  69620. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69621. },
  69622. enumerable: true,
  69623. configurable: true
  69624. });
  69625. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69626. get: function () {
  69627. return this._dPadLeft;
  69628. },
  69629. set: function (value) {
  69630. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69631. },
  69632. enumerable: true,
  69633. configurable: true
  69634. });
  69635. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69636. get: function () {
  69637. return this._dPadRight;
  69638. },
  69639. set: function (value) {
  69640. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69641. },
  69642. enumerable: true,
  69643. configurable: true
  69644. });
  69645. Xbox360Pad.prototype.update = function () {
  69646. _super.prototype.update.call(this);
  69647. if (this._isXboxOnePad) {
  69648. this.buttonA = this.browserGamepad.buttons[0].value;
  69649. this.buttonB = this.browserGamepad.buttons[1].value;
  69650. this.buttonX = this.browserGamepad.buttons[2].value;
  69651. this.buttonY = this.browserGamepad.buttons[3].value;
  69652. this.buttonLB = this.browserGamepad.buttons[4].value;
  69653. this.buttonRB = this.browserGamepad.buttons[5].value;
  69654. this.leftTrigger = this.browserGamepad.axes[2];
  69655. this.rightTrigger = this.browserGamepad.axes[5];
  69656. this.buttonBack = this.browserGamepad.buttons[9].value;
  69657. this.buttonStart = this.browserGamepad.buttons[8].value;
  69658. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69659. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69660. this.dPadUp = this.browserGamepad.buttons[11].value;
  69661. this.dPadDown = this.browserGamepad.buttons[12].value;
  69662. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69663. this.dPadRight = this.browserGamepad.buttons[14].value;
  69664. }
  69665. else {
  69666. this.buttonA = this.browserGamepad.buttons[0].value;
  69667. this.buttonB = this.browserGamepad.buttons[1].value;
  69668. this.buttonX = this.browserGamepad.buttons[2].value;
  69669. this.buttonY = this.browserGamepad.buttons[3].value;
  69670. this.buttonLB = this.browserGamepad.buttons[4].value;
  69671. this.buttonRB = this.browserGamepad.buttons[5].value;
  69672. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69673. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69674. this.buttonBack = this.browserGamepad.buttons[8].value;
  69675. this.buttonStart = this.browserGamepad.buttons[9].value;
  69676. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69677. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69678. this.dPadUp = this.browserGamepad.buttons[12].value;
  69679. this.dPadDown = this.browserGamepad.buttons[13].value;
  69680. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69681. this.dPadRight = this.browserGamepad.buttons[15].value;
  69682. }
  69683. };
  69684. Xbox360Pad.prototype.dispose = function () {
  69685. _super.prototype.dispose.call(this);
  69686. this.onButtonDownObservable.clear();
  69687. this.onButtonUpObservable.clear();
  69688. this.onPadDownObservable.clear();
  69689. this.onPadUpObservable.clear();
  69690. };
  69691. return Xbox360Pad;
  69692. }(BABYLON.Gamepad));
  69693. BABYLON.Xbox360Pad = Xbox360Pad;
  69694. })(BABYLON || (BABYLON = {}));
  69695. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69696. var BABYLON;
  69697. (function (BABYLON) {
  69698. /**
  69699. * Defines the types of pose enabled controllers that are supported
  69700. */
  69701. var PoseEnabledControllerType;
  69702. (function (PoseEnabledControllerType) {
  69703. /**
  69704. * HTC Vive
  69705. */
  69706. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69707. /**
  69708. * Oculus Rift
  69709. */
  69710. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69711. /**
  69712. * Windows mixed reality
  69713. */
  69714. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69715. /**
  69716. * Samsung gear VR
  69717. */
  69718. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69719. /**
  69720. * Google Daydream
  69721. */
  69722. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69723. /**
  69724. * Generic
  69725. */
  69726. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69727. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69728. /**
  69729. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69730. */
  69731. var PoseEnabledControllerHelper = /** @class */ (function () {
  69732. function PoseEnabledControllerHelper() {
  69733. }
  69734. /**
  69735. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69736. * @param vrGamepad the gamepad to initialized
  69737. * @returns a vr controller of the type the gamepad identified as
  69738. */
  69739. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69740. // Oculus Touch
  69741. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69742. return new BABYLON.OculusTouchController(vrGamepad);
  69743. }
  69744. // Windows Mixed Reality controllers
  69745. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69746. return new BABYLON.WindowsMotionController(vrGamepad);
  69747. }
  69748. // HTC Vive
  69749. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69750. return new BABYLON.ViveController(vrGamepad);
  69751. }
  69752. // Samsung/Oculus Gear VR
  69753. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69754. return new BABYLON.GearVRController(vrGamepad);
  69755. }
  69756. // Google Daydream
  69757. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69758. return new BABYLON.DaydreamController(vrGamepad);
  69759. }
  69760. // Generic
  69761. else {
  69762. return new BABYLON.GenericController(vrGamepad);
  69763. }
  69764. };
  69765. return PoseEnabledControllerHelper;
  69766. }());
  69767. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69768. /**
  69769. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69770. */
  69771. var PoseEnabledController = /** @class */ (function (_super) {
  69772. __extends(PoseEnabledController, _super);
  69773. /**
  69774. * Creates a new PoseEnabledController from a gamepad
  69775. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69776. */
  69777. function PoseEnabledController(browserGamepad) {
  69778. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69779. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69780. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69781. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69782. /**
  69783. * The device position in babylon space
  69784. */
  69785. _this.devicePosition = BABYLON.Vector3.Zero();
  69786. /**
  69787. * The device rotation in babylon space
  69788. */
  69789. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69790. /**
  69791. * The scale factor of the device in babylon space
  69792. */
  69793. _this.deviceScaleFactor = 1;
  69794. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69795. /**
  69796. * Internal, matrix used to convert room space to babylon space
  69797. */
  69798. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69799. /**
  69800. * Node to be used when casting a ray from the controller
  69801. */
  69802. _this._pointingPoseNode = null;
  69803. _this._workingMatrix = BABYLON.Matrix.Identity();
  69804. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69805. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69806. _this.position = BABYLON.Vector3.Zero();
  69807. _this.rotationQuaternion = new BABYLON.Quaternion();
  69808. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69809. _this._calculatedRotation = new BABYLON.Quaternion();
  69810. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69811. return _this;
  69812. }
  69813. /**
  69814. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69815. */
  69816. PoseEnabledController.prototype.update = function () {
  69817. _super.prototype.update.call(this);
  69818. var pose = this.browserGamepad.pose;
  69819. this.updateFromDevice(pose);
  69820. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69821. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69822. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69823. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69824. if (this._mesh) {
  69825. this._mesh.position.copyFrom(this.devicePosition);
  69826. if (this._mesh.rotationQuaternion) {
  69827. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69828. }
  69829. }
  69830. };
  69831. /**
  69832. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69833. * @param poseData raw pose fromthe device
  69834. */
  69835. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69836. if (poseData) {
  69837. this.rawPose = poseData;
  69838. if (poseData.position) {
  69839. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69840. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69841. this._deviceRoomPosition.z *= -1;
  69842. }
  69843. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69844. this._calculatedPosition.addInPlace(this.position);
  69845. }
  69846. var pose = this.rawPose;
  69847. if (poseData.orientation && pose.orientation) {
  69848. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69849. if (this._mesh) {
  69850. if (this._mesh.getScene().useRightHandedSystem) {
  69851. this._deviceRoomRotationQuaternion.z *= -1;
  69852. this._deviceRoomRotationQuaternion.w *= -1;
  69853. }
  69854. else {
  69855. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69856. }
  69857. }
  69858. // if the camera is set, rotate to the camera's rotation
  69859. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69860. }
  69861. }
  69862. };
  69863. /**
  69864. * Attaches a mesh to the controller
  69865. * @param mesh the mesh to be attached
  69866. */
  69867. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69868. if (this._mesh) {
  69869. this._mesh.parent = null;
  69870. }
  69871. this._mesh = mesh;
  69872. if (this._poseControlledCamera) {
  69873. this._mesh.parent = this._poseControlledCamera;
  69874. }
  69875. if (!this._mesh.rotationQuaternion) {
  69876. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69877. }
  69878. };
  69879. /**
  69880. * Attaches the controllers mesh to a camera
  69881. * @param camera the camera the mesh should be attached to
  69882. */
  69883. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69884. this._poseControlledCamera = camera;
  69885. if (this._mesh) {
  69886. this._mesh.parent = this._poseControlledCamera;
  69887. }
  69888. };
  69889. /**
  69890. * Disposes of the controller
  69891. */
  69892. PoseEnabledController.prototype.dispose = function () {
  69893. if (this._mesh) {
  69894. this._mesh.dispose();
  69895. }
  69896. this._mesh = null;
  69897. _super.prototype.dispose.call(this);
  69898. };
  69899. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69900. /**
  69901. * The mesh that is attached to the controller
  69902. */
  69903. get: function () {
  69904. return this._mesh;
  69905. },
  69906. enumerable: true,
  69907. configurable: true
  69908. });
  69909. /**
  69910. * Gets the ray of the controller in the direction the controller is pointing
  69911. * @param length the length the resulting ray should be
  69912. * @returns a ray in the direction the controller is pointing
  69913. */
  69914. PoseEnabledController.prototype.getForwardRay = function (length) {
  69915. if (length === void 0) { length = 100; }
  69916. if (!this.mesh) {
  69917. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69918. }
  69919. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69920. var origin = m.getTranslation();
  69921. var forward = new BABYLON.Vector3(0, 0, -1);
  69922. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69923. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69924. return new BABYLON.Ray(origin, direction, length);
  69925. };
  69926. /**
  69927. * Name of the child mesh that can be used to cast a ray from the controller
  69928. */
  69929. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69930. return PoseEnabledController;
  69931. }(BABYLON.Gamepad));
  69932. BABYLON.PoseEnabledController = PoseEnabledController;
  69933. })(BABYLON || (BABYLON = {}));
  69934. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69935. var BABYLON;
  69936. (function (BABYLON) {
  69937. /**
  69938. * Defines the WebVRController object that represents controllers tracked in 3D space
  69939. */
  69940. var WebVRController = /** @class */ (function (_super) {
  69941. __extends(WebVRController, _super);
  69942. /**
  69943. * Creates a new WebVRController from a gamepad
  69944. * @param vrGamepad the gamepad that the WebVRController should be created from
  69945. */
  69946. function WebVRController(vrGamepad) {
  69947. var _this = _super.call(this, vrGamepad) || this;
  69948. // Observables
  69949. /**
  69950. * Fired when the trigger state has changed
  69951. */
  69952. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69953. /**
  69954. * Fired when the main button state has changed
  69955. */
  69956. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69957. /**
  69958. * Fired when the secondary button state has changed
  69959. */
  69960. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69961. /**
  69962. * Fired when the pad state has changed
  69963. */
  69964. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69965. /**
  69966. * Fired when controllers stick values have changed
  69967. */
  69968. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69969. /**
  69970. * X and Y axis corrisponding to the controllers joystick
  69971. */
  69972. _this.pad = { x: 0, y: 0 };
  69973. // avoid GC, store state in a tmp object
  69974. _this._changes = {
  69975. pressChanged: false,
  69976. touchChanged: false,
  69977. valueChanged: false,
  69978. changed: false
  69979. };
  69980. _this._buttons = new Array(vrGamepad.buttons.length);
  69981. _this.hand = vrGamepad.hand;
  69982. return _this;
  69983. }
  69984. /**
  69985. * Fired when a controller button's state has changed
  69986. * @param callback the callback containing the button that was modified
  69987. */
  69988. WebVRController.prototype.onButtonStateChange = function (callback) {
  69989. this._onButtonStateChange = callback;
  69990. };
  69991. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69992. /**
  69993. * The default controller model for the controller
  69994. */
  69995. get: function () {
  69996. return this._defaultModel;
  69997. },
  69998. enumerable: true,
  69999. configurable: true
  70000. });
  70001. /**
  70002. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70003. */
  70004. WebVRController.prototype.update = function () {
  70005. _super.prototype.update.call(this);
  70006. for (var index = 0; index < this._buttons.length; index++) {
  70007. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70008. }
  70009. ;
  70010. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70011. this.pad.x = this.leftStick.x;
  70012. this.pad.y = this.leftStick.y;
  70013. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70014. }
  70015. };
  70016. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70017. if (!newState) {
  70018. newState = {
  70019. pressed: false,
  70020. touched: false,
  70021. value: 0
  70022. };
  70023. }
  70024. if (!currentState) {
  70025. this._buttons[buttonIndex] = {
  70026. pressed: newState.pressed,
  70027. touched: newState.touched,
  70028. value: newState.value
  70029. };
  70030. return;
  70031. }
  70032. this._checkChanges(newState, currentState);
  70033. if (this._changes.changed) {
  70034. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70035. this._handleButtonChange(buttonIndex, newState, this._changes);
  70036. }
  70037. this._buttons[buttonIndex].pressed = newState.pressed;
  70038. this._buttons[buttonIndex].touched = newState.touched;
  70039. // oculus triggers are never 0, thou not touched.
  70040. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70041. };
  70042. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70043. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70044. this._changes.touchChanged = newState.touched !== currentState.touched;
  70045. this._changes.valueChanged = newState.value !== currentState.value;
  70046. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70047. return this._changes;
  70048. };
  70049. /**
  70050. * Disposes of th webVRCOntroller
  70051. */
  70052. WebVRController.prototype.dispose = function () {
  70053. _super.prototype.dispose.call(this);
  70054. this.onTriggerStateChangedObservable.clear();
  70055. this.onMainButtonStateChangedObservable.clear();
  70056. this.onSecondaryButtonStateChangedObservable.clear();
  70057. this.onPadStateChangedObservable.clear();
  70058. this.onPadValuesChangedObservable.clear();
  70059. };
  70060. return WebVRController;
  70061. }(BABYLON.PoseEnabledController));
  70062. BABYLON.WebVRController = WebVRController;
  70063. })(BABYLON || (BABYLON = {}));
  70064. //# sourceMappingURL=babylon.webVRController.js.map
  70065. var BABYLON;
  70066. (function (BABYLON) {
  70067. /**
  70068. * Oculus Touch Controller
  70069. */
  70070. var OculusTouchController = /** @class */ (function (_super) {
  70071. __extends(OculusTouchController, _super);
  70072. /**
  70073. * Creates a new OculusTouchController from a gamepad
  70074. * @param vrGamepad the gamepad that the controller should be created from
  70075. */
  70076. function OculusTouchController(vrGamepad) {
  70077. var _this = _super.call(this, vrGamepad) || this;
  70078. /**
  70079. * Fired when the secondary trigger on this controller is modified
  70080. */
  70081. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70082. /**
  70083. * Fired when the thumb rest on this controller is modified
  70084. */
  70085. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70086. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70087. return _this;
  70088. }
  70089. /**
  70090. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70091. * @param scene scene in which to add meshes
  70092. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70093. */
  70094. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70095. var _this = this;
  70096. var meshName;
  70097. // Hand
  70098. if (this.hand === 'left') {
  70099. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70100. }
  70101. else { // Right is the default if no hand is specified
  70102. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70103. }
  70104. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70105. /*
  70106. Parent Mesh name: oculus_touch_left
  70107. - body
  70108. - trigger
  70109. - thumbstick
  70110. - grip
  70111. - button_y
  70112. - button_x
  70113. - button_enter
  70114. */
  70115. _this._defaultModel = newMeshes[1];
  70116. _this.attachToMesh(_this._defaultModel);
  70117. if (meshLoaded) {
  70118. meshLoaded(_this._defaultModel);
  70119. }
  70120. });
  70121. };
  70122. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70123. /**
  70124. * Fired when the A button on this controller is modified
  70125. */
  70126. get: function () {
  70127. if (this.hand === 'right') {
  70128. return this.onMainButtonStateChangedObservable;
  70129. }
  70130. else {
  70131. throw new Error('No A button on left hand');
  70132. }
  70133. },
  70134. enumerable: true,
  70135. configurable: true
  70136. });
  70137. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70138. /**
  70139. * Fired when the B button on this controller is modified
  70140. */
  70141. get: function () {
  70142. if (this.hand === 'right') {
  70143. return this.onSecondaryButtonStateChangedObservable;
  70144. }
  70145. else {
  70146. throw new Error('No B button on left hand');
  70147. }
  70148. },
  70149. enumerable: true,
  70150. configurable: true
  70151. });
  70152. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70153. /**
  70154. * Fired when the X button on this controller is modified
  70155. */
  70156. get: function () {
  70157. if (this.hand === 'left') {
  70158. return this.onMainButtonStateChangedObservable;
  70159. }
  70160. else {
  70161. throw new Error('No X button on right hand');
  70162. }
  70163. },
  70164. enumerable: true,
  70165. configurable: true
  70166. });
  70167. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70168. /**
  70169. * Fired when the Y button on this controller is modified
  70170. */
  70171. get: function () {
  70172. if (this.hand === 'left') {
  70173. return this.onSecondaryButtonStateChangedObservable;
  70174. }
  70175. else {
  70176. throw new Error('No Y button on right hand');
  70177. }
  70178. },
  70179. enumerable: true,
  70180. configurable: true
  70181. });
  70182. /**
  70183. * Called once for each button that changed state since the last frame
  70184. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70185. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70186. * 2) secondary trigger (same)
  70187. * 3) A (right) X (left), touch, pressed = value
  70188. * 4) B / Y
  70189. * 5) thumb rest
  70190. * @param buttonIdx Which button index changed
  70191. * @param state New state of the button
  70192. * @param changes Which properties on the state changed since last frame
  70193. */
  70194. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70195. var notifyObject = state; //{ state: state, changes: changes };
  70196. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70197. switch (buttonIdx) {
  70198. case 0:
  70199. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70200. return;
  70201. case 1: // index trigger
  70202. if (this._defaultModel) {
  70203. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70204. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70205. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70206. }
  70207. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70208. return;
  70209. case 2: // secondary trigger
  70210. if (this._defaultModel) {
  70211. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70212. }
  70213. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70214. return;
  70215. case 3:
  70216. if (this._defaultModel) {
  70217. if (notifyObject.pressed) {
  70218. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70219. }
  70220. else {
  70221. (this._defaultModel.getChildren()[1]).position.y = 0;
  70222. }
  70223. }
  70224. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70225. return;
  70226. case 4:
  70227. if (this._defaultModel) {
  70228. if (notifyObject.pressed) {
  70229. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70230. }
  70231. else {
  70232. (this._defaultModel.getChildren()[2]).position.y = 0;
  70233. }
  70234. }
  70235. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70236. return;
  70237. case 5:
  70238. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70239. return;
  70240. }
  70241. };
  70242. /**
  70243. * Base Url for the controller model.
  70244. */
  70245. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70246. /**
  70247. * File name for the left controller model.
  70248. */
  70249. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70250. /**
  70251. * File name for the right controller model.
  70252. */
  70253. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70254. return OculusTouchController;
  70255. }(BABYLON.WebVRController));
  70256. BABYLON.OculusTouchController = OculusTouchController;
  70257. })(BABYLON || (BABYLON = {}));
  70258. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70259. var BABYLON;
  70260. (function (BABYLON) {
  70261. /**
  70262. * Vive Controller
  70263. */
  70264. var ViveController = /** @class */ (function (_super) {
  70265. __extends(ViveController, _super);
  70266. /**
  70267. * Creates a new ViveController from a gamepad
  70268. * @param vrGamepad the gamepad that the controller should be created from
  70269. */
  70270. function ViveController(vrGamepad) {
  70271. var _this = _super.call(this, vrGamepad) || this;
  70272. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70273. _this._invertLeftStickY = true;
  70274. return _this;
  70275. }
  70276. /**
  70277. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70278. * @param scene scene in which to add meshes
  70279. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70280. */
  70281. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70282. var _this = this;
  70283. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70284. /*
  70285. Parent Mesh name: ViveWand
  70286. - body
  70287. - r_gripper
  70288. - l_gripper
  70289. - menu_button
  70290. - system_button
  70291. - trackpad
  70292. - trigger
  70293. - LED
  70294. */
  70295. _this._defaultModel = newMeshes[1];
  70296. _this.attachToMesh(_this._defaultModel);
  70297. if (meshLoaded) {
  70298. meshLoaded(_this._defaultModel);
  70299. }
  70300. });
  70301. };
  70302. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70303. /**
  70304. * Fired when the left button on this controller is modified
  70305. */
  70306. get: function () {
  70307. return this.onMainButtonStateChangedObservable;
  70308. },
  70309. enumerable: true,
  70310. configurable: true
  70311. });
  70312. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70313. /**
  70314. * Fired when the right button on this controller is modified
  70315. */
  70316. get: function () {
  70317. return this.onMainButtonStateChangedObservable;
  70318. },
  70319. enumerable: true,
  70320. configurable: true
  70321. });
  70322. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70323. /**
  70324. * Fired when the menu button on this controller is modified
  70325. */
  70326. get: function () {
  70327. return this.onSecondaryButtonStateChangedObservable;
  70328. },
  70329. enumerable: true,
  70330. configurable: true
  70331. });
  70332. /**
  70333. * Called once for each button that changed state since the last frame
  70334. * Vive mapping:
  70335. * 0: touchpad
  70336. * 1: trigger
  70337. * 2: left AND right buttons
  70338. * 3: menu button
  70339. * @param buttonIdx Which button index changed
  70340. * @param state New state of the button
  70341. * @param changes Which properties on the state changed since last frame
  70342. */
  70343. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70344. var notifyObject = state; //{ state: state, changes: changes };
  70345. switch (buttonIdx) {
  70346. case 0:
  70347. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70348. return;
  70349. case 1: // index trigger
  70350. if (this._defaultModel) {
  70351. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70352. }
  70353. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70354. return;
  70355. case 2: // left AND right button
  70356. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70357. return;
  70358. case 3:
  70359. if (this._defaultModel) {
  70360. if (notifyObject.pressed) {
  70361. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70362. }
  70363. else {
  70364. (this._defaultModel.getChildren()[2]).position.y = 0;
  70365. }
  70366. }
  70367. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70368. return;
  70369. }
  70370. };
  70371. /**
  70372. * Base Url for the controller model.
  70373. */
  70374. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70375. /**
  70376. * File name for the controller model.
  70377. */
  70378. ViveController.MODEL_FILENAME = 'wand.babylon';
  70379. return ViveController;
  70380. }(BABYLON.WebVRController));
  70381. BABYLON.ViveController = ViveController;
  70382. })(BABYLON || (BABYLON = {}));
  70383. //# sourceMappingURL=babylon.viveController.js.map
  70384. var BABYLON;
  70385. (function (BABYLON) {
  70386. /**
  70387. * Generic Controller
  70388. */
  70389. var GenericController = /** @class */ (function (_super) {
  70390. __extends(GenericController, _super);
  70391. /**
  70392. * Creates a new GenericController from a gamepad
  70393. * @param vrGamepad the gamepad that the controller should be created from
  70394. */
  70395. function GenericController(vrGamepad) {
  70396. return _super.call(this, vrGamepad) || this;
  70397. }
  70398. /**
  70399. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70400. * @param scene scene in which to add meshes
  70401. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70402. */
  70403. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70404. var _this = this;
  70405. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70406. _this._defaultModel = newMeshes[1];
  70407. _this.attachToMesh(_this._defaultModel);
  70408. if (meshLoaded) {
  70409. meshLoaded(_this._defaultModel);
  70410. }
  70411. });
  70412. };
  70413. /**
  70414. * Called once for each button that changed state since the last frame
  70415. * @param buttonIdx Which button index changed
  70416. * @param state New state of the button
  70417. * @param changes Which properties on the state changed since last frame
  70418. */
  70419. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70420. console.log("Button id: " + buttonIdx + "state: ");
  70421. console.dir(state);
  70422. };
  70423. /**
  70424. * Base Url for the controller model.
  70425. */
  70426. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70427. /**
  70428. * File name for the controller model.
  70429. */
  70430. GenericController.MODEL_FILENAME = 'generic.babylon';
  70431. return GenericController;
  70432. }(BABYLON.WebVRController));
  70433. BABYLON.GenericController = GenericController;
  70434. })(BABYLON || (BABYLON = {}));
  70435. //# sourceMappingURL=babylon.genericController.js.map
  70436. var BABYLON;
  70437. (function (BABYLON) {
  70438. /**
  70439. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70440. */
  70441. var LoadedMeshInfo = /** @class */ (function () {
  70442. function LoadedMeshInfo() {
  70443. /**
  70444. * Map of the button meshes contained in the controller
  70445. */
  70446. this.buttonMeshes = {};
  70447. /**
  70448. * Map of the axis meshes contained in the controller
  70449. */
  70450. this.axisMeshes = {};
  70451. }
  70452. return LoadedMeshInfo;
  70453. }());
  70454. /**
  70455. * Defines the WindowsMotionController object that the state of the windows motion controller
  70456. */
  70457. var WindowsMotionController = /** @class */ (function (_super) {
  70458. __extends(WindowsMotionController, _super);
  70459. /**
  70460. * Creates a new WindowsMotionController from a gamepad
  70461. * @param vrGamepad the gamepad that the controller should be created from
  70462. */
  70463. function WindowsMotionController(vrGamepad) {
  70464. var _this = _super.call(this, vrGamepad) || this;
  70465. _this._mapping = {
  70466. // Semantic button names
  70467. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70468. // A mapping of the button name to glTF model node name
  70469. // that should be transformed by button value.
  70470. buttonMeshNames: {
  70471. 'trigger': 'SELECT',
  70472. 'menu': 'MENU',
  70473. 'grip': 'GRASP',
  70474. 'thumbstick': 'THUMBSTICK_PRESS',
  70475. 'trackpad': 'TOUCHPAD_PRESS'
  70476. },
  70477. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70478. buttonObservableNames: {
  70479. 'trigger': 'onTriggerStateChangedObservable',
  70480. 'menu': 'onSecondaryButtonStateChangedObservable',
  70481. 'grip': 'onMainButtonStateChangedObservable',
  70482. 'thumbstick': 'onPadStateChangedObservable',
  70483. 'trackpad': 'onTrackpadChangedObservable'
  70484. },
  70485. // A mapping of the axis name to glTF model node name
  70486. // that should be transformed by axis value.
  70487. // This array mirrors the browserGamepad.axes array, such that
  70488. // the mesh corresponding to axis 0 is in this array index 0.
  70489. axisMeshNames: [
  70490. 'THUMBSTICK_X',
  70491. 'THUMBSTICK_Y',
  70492. 'TOUCHPAD_TOUCH_X',
  70493. 'TOUCHPAD_TOUCH_Y'
  70494. ],
  70495. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70496. };
  70497. /**
  70498. * Fired when the trackpad on this controller is clicked
  70499. */
  70500. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70501. /**
  70502. * Fired when the trackpad on this controller is modified
  70503. */
  70504. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70505. /**
  70506. * The current x and y values of this controller's trackpad
  70507. */
  70508. _this.trackpad = { x: 0, y: 0 };
  70509. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70510. _this._loadedMeshInfo = null;
  70511. return _this;
  70512. }
  70513. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70514. /**
  70515. * Fired when the trigger on this controller is modified
  70516. */
  70517. get: function () {
  70518. return this.onTriggerStateChangedObservable;
  70519. },
  70520. enumerable: true,
  70521. configurable: true
  70522. });
  70523. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70524. /**
  70525. * Fired when the menu button on this controller is modified
  70526. */
  70527. get: function () {
  70528. return this.onSecondaryButtonStateChangedObservable;
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70534. /**
  70535. * Fired when the grip button on this controller is modified
  70536. */
  70537. get: function () {
  70538. return this.onMainButtonStateChangedObservable;
  70539. },
  70540. enumerable: true,
  70541. configurable: true
  70542. });
  70543. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70544. /**
  70545. * Fired when the thumbstick button on this controller is modified
  70546. */
  70547. get: function () {
  70548. return this.onPadStateChangedObservable;
  70549. },
  70550. enumerable: true,
  70551. configurable: true
  70552. });
  70553. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70554. /**
  70555. * Fired when the touchpad button on this controller is modified
  70556. */
  70557. get: function () {
  70558. return this.onTrackpadChangedObservable;
  70559. },
  70560. enumerable: true,
  70561. configurable: true
  70562. });
  70563. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70564. /**
  70565. * Fired when the touchpad values on this controller are modified
  70566. */
  70567. get: function () {
  70568. return this.onTrackpadValuesChangedObservable;
  70569. },
  70570. enumerable: true,
  70571. configurable: true
  70572. });
  70573. /**
  70574. * Called once per frame by the engine.
  70575. */
  70576. WindowsMotionController.prototype.update = function () {
  70577. _super.prototype.update.call(this);
  70578. if (this.browserGamepad.axes) {
  70579. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70580. this.trackpad.x = this.browserGamepad["axes"][2];
  70581. this.trackpad.y = this.browserGamepad["axes"][3];
  70582. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70583. }
  70584. // Only need to animate axes if there is a loaded mesh
  70585. if (this._loadedMeshInfo) {
  70586. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70587. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70588. }
  70589. }
  70590. }
  70591. };
  70592. /**
  70593. * Called once for each button that changed state since the last frame
  70594. * @param buttonIdx Which button index changed
  70595. * @param state New state of the button
  70596. * @param changes Which properties on the state changed since last frame
  70597. */
  70598. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70599. var buttonName = this._mapping.buttons[buttonIdx];
  70600. if (!buttonName) {
  70601. return;
  70602. }
  70603. // Only emit events for buttons that we know how to map from index to name
  70604. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70605. if (observable) {
  70606. observable.notifyObservers(state);
  70607. }
  70608. this._lerpButtonTransform(buttonName, state.value);
  70609. };
  70610. /**
  70611. * Moves the buttons on the controller mesh based on their current state
  70612. * @param buttonName the name of the button to move
  70613. * @param buttonValue the value of the button which determines the buttons new position
  70614. */
  70615. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70616. // If there is no loaded mesh, there is nothing to transform.
  70617. if (!this._loadedMeshInfo) {
  70618. return;
  70619. }
  70620. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70621. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70622. return;
  70623. }
  70624. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70625. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70626. };
  70627. /**
  70628. * Moves the axis on the controller mesh based on its current state
  70629. * @param axis the index of the axis
  70630. * @param axisValue the value of the axis which determines the meshes new position
  70631. * @ignore
  70632. */
  70633. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70634. if (!this._loadedMeshInfo) {
  70635. return;
  70636. }
  70637. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70638. if (!meshInfo) {
  70639. return;
  70640. }
  70641. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70642. return;
  70643. }
  70644. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70645. var lerpValue = axisValue * 0.5 + 0.5;
  70646. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70647. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70648. };
  70649. /**
  70650. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70651. * @param scene scene in which to add meshes
  70652. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70653. */
  70654. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70655. var _this = this;
  70656. if (forceDefault === void 0) { forceDefault = false; }
  70657. var path;
  70658. var filename;
  70659. // Checking if GLB loader is present
  70660. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70661. // Determine the device specific folder based on the ID suffix
  70662. var device = 'default';
  70663. if (this.id && !forceDefault) {
  70664. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70665. device = ((match && match[0]) || device);
  70666. }
  70667. // Hand
  70668. if (this.hand === 'left') {
  70669. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70670. }
  70671. else { // Right is the default if no hand is specified
  70672. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70673. }
  70674. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70675. }
  70676. else {
  70677. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70678. path = BABYLON.GenericController.MODEL_BASE_URL;
  70679. filename = BABYLON.GenericController.MODEL_FILENAME;
  70680. }
  70681. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70682. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70683. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70684. if (!_this._loadedMeshInfo) {
  70685. return;
  70686. }
  70687. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70688. _this.attachToMesh(_this._defaultModel);
  70689. if (meshLoaded) {
  70690. meshLoaded(_this._defaultModel);
  70691. }
  70692. }, null, function (scene, message) {
  70693. BABYLON.Tools.Log(message);
  70694. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70695. if (!forceDefault) {
  70696. _this.initControllerMesh(scene, meshLoaded, true);
  70697. }
  70698. });
  70699. };
  70700. /**
  70701. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70702. * can be transformed by button presses and axes values, based on this._mapping.
  70703. *
  70704. * @param scene scene in which the meshes exist
  70705. * @param meshes list of meshes that make up the controller model to process
  70706. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70707. */
  70708. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70709. var loadedMeshInfo = null;
  70710. // Create a new mesh to contain the glTF hierarchy
  70711. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70712. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70713. var childMesh = null;
  70714. for (var i = 0; i < meshes.length; i++) {
  70715. var mesh = meshes[i];
  70716. if (!mesh.parent) {
  70717. // Exclude controller meshes from picking results
  70718. mesh.isPickable = false;
  70719. // Handle root node, attach to the new parentMesh
  70720. childMesh = mesh;
  70721. break;
  70722. }
  70723. }
  70724. if (childMesh) {
  70725. childMesh.setParent(parentMesh);
  70726. // Create our mesh info. Note that this method will always return non-null.
  70727. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70728. }
  70729. else {
  70730. BABYLON.Tools.Warn('Could not find root node in model file.');
  70731. }
  70732. return loadedMeshInfo;
  70733. };
  70734. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70735. var loadedMeshInfo = new LoadedMeshInfo();
  70736. var i;
  70737. loadedMeshInfo.rootNode = rootNode;
  70738. // Reset the caches
  70739. loadedMeshInfo.buttonMeshes = {};
  70740. loadedMeshInfo.axisMeshes = {};
  70741. // Button Meshes
  70742. for (i = 0; i < this._mapping.buttons.length; i++) {
  70743. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70744. if (!buttonMeshName) {
  70745. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70746. continue;
  70747. }
  70748. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70749. if (!buttonMesh) {
  70750. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70751. continue;
  70752. }
  70753. var buttonMeshInfo = {
  70754. index: i,
  70755. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70756. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70757. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70758. };
  70759. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70760. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70761. }
  70762. else {
  70763. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70764. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70765. '(VALUE: ' + !!buttonMeshInfo.value +
  70766. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70767. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70768. ')');
  70769. }
  70770. }
  70771. // Axis Meshes
  70772. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70773. var axisMeshName = this._mapping.axisMeshNames[i];
  70774. if (!axisMeshName) {
  70775. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70776. continue;
  70777. }
  70778. var axisMesh = getChildByName(rootNode, axisMeshName);
  70779. if (!axisMesh) {
  70780. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70781. continue;
  70782. }
  70783. var axisMeshInfo = {
  70784. index: i,
  70785. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70786. min: getImmediateChildByName(axisMesh, 'MIN'),
  70787. max: getImmediateChildByName(axisMesh, 'MAX')
  70788. };
  70789. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70790. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70791. }
  70792. else {
  70793. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70794. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70795. '(VALUE: ' + !!axisMeshInfo.value +
  70796. ', MIN: ' + !!axisMeshInfo.min +
  70797. ', MAX:' + !!axisMeshInfo.max +
  70798. ')');
  70799. }
  70800. }
  70801. // Pointing Ray
  70802. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70803. if (!loadedMeshInfo.pointingPoseNode) {
  70804. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70805. }
  70806. return loadedMeshInfo;
  70807. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70808. function getChildByName(node, name) {
  70809. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70810. }
  70811. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70812. function getImmediateChildByName(node, name) {
  70813. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70814. }
  70815. };
  70816. /**
  70817. * Gets the ray of the controller in the direction the controller is pointing
  70818. * @param length the length the resulting ray should be
  70819. * @returns a ray in the direction the controller is pointing
  70820. */
  70821. WindowsMotionController.prototype.getForwardRay = function (length) {
  70822. if (length === void 0) { length = 100; }
  70823. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70824. return _super.prototype.getForwardRay.call(this, length);
  70825. }
  70826. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70827. var origin = m.getTranslation();
  70828. var forward = new BABYLON.Vector3(0, 0, -1);
  70829. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70830. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70831. return new BABYLON.Ray(origin, direction, length);
  70832. };
  70833. /**
  70834. * Disposes of the controller
  70835. */
  70836. WindowsMotionController.prototype.dispose = function () {
  70837. _super.prototype.dispose.call(this);
  70838. this.onTrackpadChangedObservable.clear();
  70839. };
  70840. /**
  70841. * The base url used to load the left and right controller models
  70842. */
  70843. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70844. /**
  70845. * The name of the left controller model file
  70846. */
  70847. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70848. /**
  70849. * The name of the right controller model file
  70850. */
  70851. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70852. /**
  70853. * The controller name prefix for this controller type
  70854. */
  70855. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70856. /**
  70857. * The controller id pattern for this controller type
  70858. */
  70859. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70860. return WindowsMotionController;
  70861. }(BABYLON.WebVRController));
  70862. BABYLON.WindowsMotionController = WindowsMotionController;
  70863. })(BABYLON || (BABYLON = {}));
  70864. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70865. var BABYLON;
  70866. (function (BABYLON) {
  70867. /**
  70868. * Gear VR Controller
  70869. */
  70870. var GearVRController = /** @class */ (function (_super) {
  70871. __extends(GearVRController, _super);
  70872. /**
  70873. * Creates a new GearVRController from a gamepad
  70874. * @param vrGamepad the gamepad that the controller should be created from
  70875. */
  70876. function GearVRController(vrGamepad) {
  70877. var _this = _super.call(this, vrGamepad) || this;
  70878. _this._buttonIndexToObservableNameMap = [
  70879. 'onTrackpadChangedObservable',
  70880. 'onTriggerStateChangedObservable' // Trigger
  70881. ];
  70882. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70883. return _this;
  70884. }
  70885. /**
  70886. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70887. * @param scene scene in which to add meshes
  70888. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70889. */
  70890. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70891. var _this = this;
  70892. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70893. _this._defaultModel = newMeshes[1];
  70894. _this.attachToMesh(_this._defaultModel);
  70895. if (meshLoaded) {
  70896. meshLoaded(_this._defaultModel);
  70897. }
  70898. });
  70899. };
  70900. /**
  70901. * Called once for each button that changed state since the last frame
  70902. * @param buttonIdx Which button index changed
  70903. * @param state New state of the button
  70904. * @param changes Which properties on the state changed since last frame
  70905. */
  70906. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70907. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70908. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70909. // Only emit events for buttons that we know how to map from index to observable
  70910. var observable = this[observableName];
  70911. if (observable) {
  70912. observable.notifyObservers(state);
  70913. }
  70914. }
  70915. };
  70916. /**
  70917. * Base Url for the controller model.
  70918. */
  70919. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70920. /**
  70921. * File name for the controller model.
  70922. */
  70923. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70924. /**
  70925. * Gamepad Id prefix used to identify this controller.
  70926. */
  70927. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70928. return GearVRController;
  70929. }(BABYLON.WebVRController));
  70930. BABYLON.GearVRController = GearVRController;
  70931. })(BABYLON || (BABYLON = {}));
  70932. //# sourceMappingURL=babylon.gearVRController.js.map
  70933. var BABYLON;
  70934. (function (BABYLON) {
  70935. /**
  70936. * Google Daydream controller
  70937. */
  70938. var DaydreamController = /** @class */ (function (_super) {
  70939. __extends(DaydreamController, _super);
  70940. /**
  70941. * Creates a new DaydreamController from a gamepad
  70942. * @param vrGamepad the gamepad that the controller should be created from
  70943. */
  70944. function DaydreamController(vrGamepad) {
  70945. var _this = _super.call(this, vrGamepad) || this;
  70946. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70947. return _this;
  70948. }
  70949. /**
  70950. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70951. * @param scene scene in which to add meshes
  70952. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70953. */
  70954. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70955. var _this = this;
  70956. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70957. _this._defaultModel = newMeshes[1];
  70958. _this.attachToMesh(_this._defaultModel);
  70959. if (meshLoaded) {
  70960. meshLoaded(_this._defaultModel);
  70961. }
  70962. });
  70963. };
  70964. /**
  70965. * Called once for each button that changed state since the last frame
  70966. * @param buttonIdx Which button index changed
  70967. * @param state New state of the button
  70968. * @param changes Which properties on the state changed since last frame
  70969. */
  70970. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70971. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70972. if (buttonIdx === 0) {
  70973. var observable = this.onTriggerStateChangedObservable;
  70974. if (observable) {
  70975. observable.notifyObservers(state);
  70976. }
  70977. }
  70978. else {
  70979. // If the app or home buttons are ever made available
  70980. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70981. }
  70982. };
  70983. /**
  70984. * Base Url for the controller model.
  70985. */
  70986. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70987. /**
  70988. * File name for the controller model.
  70989. */
  70990. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70991. /**
  70992. * Gamepad Id prefix used to identify Daydream Controller.
  70993. */
  70994. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70995. return DaydreamController;
  70996. }(BABYLON.WebVRController));
  70997. BABYLON.DaydreamController = DaydreamController;
  70998. })(BABYLON || (BABYLON = {}));
  70999. //# sourceMappingURL=babylon.daydreamController.js.map
  71000. var BABYLON;
  71001. (function (BABYLON) {
  71002. var FollowCamera = /** @class */ (function (_super) {
  71003. __extends(FollowCamera, _super);
  71004. function FollowCamera(name, position, scene, lockedTarget) {
  71005. if (lockedTarget === void 0) { lockedTarget = null; }
  71006. var _this = _super.call(this, name, position, scene) || this;
  71007. _this.radius = 12;
  71008. _this.rotationOffset = 0;
  71009. _this.heightOffset = 4;
  71010. _this.cameraAcceleration = 0.05;
  71011. _this.maxCameraSpeed = 20;
  71012. _this.lockedTarget = lockedTarget;
  71013. return _this;
  71014. }
  71015. FollowCamera.prototype.getRadians = function (degrees) {
  71016. return degrees * Math.PI / 180;
  71017. };
  71018. FollowCamera.prototype.follow = function (cameraTarget) {
  71019. if (!cameraTarget)
  71020. return;
  71021. var yRotation;
  71022. if (cameraTarget.rotationQuaternion) {
  71023. var rotMatrix = new BABYLON.Matrix();
  71024. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71025. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71026. }
  71027. else {
  71028. yRotation = cameraTarget.rotation.y;
  71029. }
  71030. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71031. var targetPosition = cameraTarget.getAbsolutePosition();
  71032. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71033. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71034. var dx = targetX - this.position.x;
  71035. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71036. var dz = (targetZ) - this.position.z;
  71037. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71038. var vy = dy * this.cameraAcceleration;
  71039. var vz = dz * this.cameraAcceleration * 2;
  71040. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71041. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71042. }
  71043. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71044. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71045. }
  71046. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71047. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71048. }
  71049. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71050. this.setTarget(targetPosition);
  71051. };
  71052. FollowCamera.prototype._checkInputs = function () {
  71053. _super.prototype._checkInputs.call(this);
  71054. if (this.lockedTarget) {
  71055. this.follow(this.lockedTarget);
  71056. }
  71057. };
  71058. FollowCamera.prototype.getClassName = function () {
  71059. return "FollowCamera";
  71060. };
  71061. __decorate([
  71062. BABYLON.serialize()
  71063. ], FollowCamera.prototype, "radius", void 0);
  71064. __decorate([
  71065. BABYLON.serialize()
  71066. ], FollowCamera.prototype, "rotationOffset", void 0);
  71067. __decorate([
  71068. BABYLON.serialize()
  71069. ], FollowCamera.prototype, "heightOffset", void 0);
  71070. __decorate([
  71071. BABYLON.serialize()
  71072. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71073. __decorate([
  71074. BABYLON.serialize()
  71075. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71076. __decorate([
  71077. BABYLON.serializeAsMeshReference("lockedTargetId")
  71078. ], FollowCamera.prototype, "lockedTarget", void 0);
  71079. return FollowCamera;
  71080. }(BABYLON.TargetCamera));
  71081. BABYLON.FollowCamera = FollowCamera;
  71082. var ArcFollowCamera = /** @class */ (function (_super) {
  71083. __extends(ArcFollowCamera, _super);
  71084. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71085. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71086. _this.alpha = alpha;
  71087. _this.beta = beta;
  71088. _this.radius = radius;
  71089. _this.target = target;
  71090. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71091. _this.follow();
  71092. return _this;
  71093. }
  71094. ArcFollowCamera.prototype.follow = function () {
  71095. if (!this.target) {
  71096. return;
  71097. }
  71098. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71099. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71100. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71101. var targetPosition = this.target.getAbsolutePosition();
  71102. this.position = targetPosition.add(this._cartesianCoordinates);
  71103. this.setTarget(targetPosition);
  71104. };
  71105. ArcFollowCamera.prototype._checkInputs = function () {
  71106. _super.prototype._checkInputs.call(this);
  71107. this.follow();
  71108. };
  71109. ArcFollowCamera.prototype.getClassName = function () {
  71110. return "ArcFollowCamera";
  71111. };
  71112. return ArcFollowCamera;
  71113. }(BABYLON.TargetCamera));
  71114. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71115. })(BABYLON || (BABYLON = {}));
  71116. //# sourceMappingURL=babylon.followCamera.js.map
  71117. var BABYLON;
  71118. (function (BABYLON) {
  71119. // We're mainly based on the logic defined into the FreeCamera code
  71120. var UniversalCamera = /** @class */ (function (_super) {
  71121. __extends(UniversalCamera, _super);
  71122. //-- end properties for backward compatibility for inputs
  71123. function UniversalCamera(name, position, scene) {
  71124. var _this = _super.call(this, name, position, scene) || this;
  71125. _this.inputs.addGamepad();
  71126. return _this;
  71127. }
  71128. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71129. //-- Begin properties for backward compatibility for inputs
  71130. get: function () {
  71131. var gamepad = this.inputs.attached["gamepad"];
  71132. if (gamepad)
  71133. return gamepad.gamepadAngularSensibility;
  71134. return 0;
  71135. },
  71136. set: function (value) {
  71137. var gamepad = this.inputs.attached["gamepad"];
  71138. if (gamepad)
  71139. gamepad.gamepadAngularSensibility = value;
  71140. },
  71141. enumerable: true,
  71142. configurable: true
  71143. });
  71144. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71145. get: function () {
  71146. var gamepad = this.inputs.attached["gamepad"];
  71147. if (gamepad)
  71148. return gamepad.gamepadMoveSensibility;
  71149. return 0;
  71150. },
  71151. set: function (value) {
  71152. var gamepad = this.inputs.attached["gamepad"];
  71153. if (gamepad)
  71154. gamepad.gamepadMoveSensibility = value;
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. UniversalCamera.prototype.getClassName = function () {
  71160. return "UniversalCamera";
  71161. };
  71162. return UniversalCamera;
  71163. }(BABYLON.TouchCamera));
  71164. BABYLON.UniversalCamera = UniversalCamera;
  71165. })(BABYLON || (BABYLON = {}));
  71166. //# sourceMappingURL=babylon.universalCamera.js.map
  71167. var BABYLON;
  71168. (function (BABYLON) {
  71169. // We're mainly based on the logic defined into the FreeCamera code
  71170. var GamepadCamera = /** @class */ (function (_super) {
  71171. __extends(GamepadCamera, _super);
  71172. //-- end properties for backward compatibility for inputs
  71173. function GamepadCamera(name, position, scene) {
  71174. return _super.call(this, name, position, scene) || this;
  71175. }
  71176. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71177. //-- Begin properties for backward compatibility for inputs
  71178. get: function () {
  71179. var gamepad = this.inputs.attached["gamepad"];
  71180. if (gamepad)
  71181. return gamepad.gamepadAngularSensibility;
  71182. return 0;
  71183. },
  71184. set: function (value) {
  71185. var gamepad = this.inputs.attached["gamepad"];
  71186. if (gamepad)
  71187. gamepad.gamepadAngularSensibility = value;
  71188. },
  71189. enumerable: true,
  71190. configurable: true
  71191. });
  71192. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71193. get: function () {
  71194. var gamepad = this.inputs.attached["gamepad"];
  71195. if (gamepad)
  71196. return gamepad.gamepadMoveSensibility;
  71197. return 0;
  71198. },
  71199. set: function (value) {
  71200. var gamepad = this.inputs.attached["gamepad"];
  71201. if (gamepad)
  71202. gamepad.gamepadMoveSensibility = value;
  71203. },
  71204. enumerable: true,
  71205. configurable: true
  71206. });
  71207. GamepadCamera.prototype.getClassName = function () {
  71208. return "GamepadCamera";
  71209. };
  71210. return GamepadCamera;
  71211. }(BABYLON.UniversalCamera));
  71212. BABYLON.GamepadCamera = GamepadCamera;
  71213. })(BABYLON || (BABYLON = {}));
  71214. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71215. var BABYLON;
  71216. (function (BABYLON) {
  71217. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71218. function PostProcessRenderPipelineManager() {
  71219. this._renderPipelines = {};
  71220. }
  71221. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71222. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71223. };
  71224. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71225. if (unique === void 0) { unique = false; }
  71226. var renderPipeline = this._renderPipelines[renderPipelineName];
  71227. if (!renderPipeline) {
  71228. return;
  71229. }
  71230. renderPipeline._attachCameras(cameras, unique);
  71231. };
  71232. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71233. var renderPipeline = this._renderPipelines[renderPipelineName];
  71234. if (!renderPipeline) {
  71235. return;
  71236. }
  71237. renderPipeline._detachCameras(cameras);
  71238. };
  71239. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71240. var renderPipeline = this._renderPipelines[renderPipelineName];
  71241. if (!renderPipeline) {
  71242. return;
  71243. }
  71244. renderPipeline._enableEffect(renderEffectName, cameras);
  71245. };
  71246. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71247. var renderPipeline = this._renderPipelines[renderPipelineName];
  71248. if (!renderPipeline) {
  71249. return;
  71250. }
  71251. renderPipeline._disableEffect(renderEffectName, cameras);
  71252. };
  71253. PostProcessRenderPipelineManager.prototype.update = function () {
  71254. for (var renderPipelineName in this._renderPipelines) {
  71255. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71256. var pipeline = this._renderPipelines[renderPipelineName];
  71257. if (!pipeline.isSupported) {
  71258. pipeline.dispose();
  71259. delete this._renderPipelines[renderPipelineName];
  71260. }
  71261. else {
  71262. pipeline._update();
  71263. }
  71264. }
  71265. }
  71266. };
  71267. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71268. for (var renderPipelineName in this._renderPipelines) {
  71269. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71270. var pipeline = this._renderPipelines[renderPipelineName];
  71271. pipeline._rebuild();
  71272. }
  71273. }
  71274. };
  71275. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71276. for (var renderPipelineName in this._renderPipelines) {
  71277. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71278. var pipeline = this._renderPipelines[renderPipelineName];
  71279. pipeline.dispose();
  71280. }
  71281. }
  71282. };
  71283. return PostProcessRenderPipelineManager;
  71284. }());
  71285. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71286. })(BABYLON || (BABYLON = {}));
  71287. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71288. var BABYLON;
  71289. (function (BABYLON) {
  71290. /**
  71291. * This represents a set of one or more post processes in Babylon.
  71292. * A post process can be used to apply a shader to a texture after it is rendered.
  71293. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71294. */
  71295. var PostProcessRenderEffect = /** @class */ (function () {
  71296. /**
  71297. * Instantiates a post process render effect.
  71298. * A post process can be used to apply a shader to a texture after it is rendered.
  71299. * @param engine The engine the effect is tied to
  71300. * @param name The name of the effect
  71301. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71302. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71303. */
  71304. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71305. this._name = name;
  71306. this._singleInstance = singleInstance || true;
  71307. this._getPostProcesses = getPostProcesses;
  71308. this._cameras = {};
  71309. this._indicesForCamera = {};
  71310. this._postProcesses = {};
  71311. }
  71312. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71313. /**
  71314. * Checks if all the post processes in the effect are supported.
  71315. */
  71316. get: function () {
  71317. for (var index in this._postProcesses) {
  71318. if (this._postProcesses.hasOwnProperty(index)) {
  71319. var pps = this._postProcesses[index];
  71320. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71321. if (!pps[ppIndex].isSupported) {
  71322. return false;
  71323. }
  71324. }
  71325. }
  71326. }
  71327. return true;
  71328. },
  71329. enumerable: true,
  71330. configurable: true
  71331. });
  71332. /**
  71333. * Updates the current state of the effect
  71334. */
  71335. PostProcessRenderEffect.prototype._update = function () {
  71336. };
  71337. /**
  71338. * Attaches the effect on cameras
  71339. * @param cameras The camera to attach to.
  71340. */
  71341. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71342. var _this = this;
  71343. var cameraKey;
  71344. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71345. if (!cams) {
  71346. return;
  71347. }
  71348. for (var i = 0; i < cams.length; i++) {
  71349. var camera = cams[i];
  71350. var cameraName = camera.name;
  71351. if (this._singleInstance) {
  71352. cameraKey = 0;
  71353. }
  71354. else {
  71355. cameraKey = cameraName;
  71356. }
  71357. if (!this._postProcesses[cameraKey]) {
  71358. var postProcess = this._getPostProcesses();
  71359. if (postProcess) {
  71360. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71361. }
  71362. }
  71363. if (!this._indicesForCamera[cameraName]) {
  71364. this._indicesForCamera[cameraName] = [];
  71365. }
  71366. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71367. var index = camera.attachPostProcess(postProcess);
  71368. _this._indicesForCamera[cameraName].push(index);
  71369. });
  71370. if (!this._cameras[cameraName]) {
  71371. this._cameras[cameraName] = camera;
  71372. }
  71373. }
  71374. };
  71375. /**
  71376. * Detatches the effect on cameras
  71377. * @param cameras The camera to detatch from.
  71378. */
  71379. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71380. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71381. if (!cams) {
  71382. return;
  71383. }
  71384. for (var i = 0; i < cams.length; i++) {
  71385. var camera = cams[i];
  71386. var cameraName = camera.name;
  71387. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71388. camera.detachPostProcess(postProcess);
  71389. });
  71390. if (this._cameras[cameraName]) {
  71391. //this._indicesForCamera.splice(index, 1);
  71392. this._cameras[cameraName] = null;
  71393. }
  71394. }
  71395. };
  71396. /**
  71397. * Enables the effect on given cameras
  71398. * @param cameras The camera to enable.
  71399. */
  71400. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71401. var _this = this;
  71402. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71403. if (!cams) {
  71404. return;
  71405. }
  71406. for (var i = 0; i < cams.length; i++) {
  71407. var camera = cams[i];
  71408. var cameraName = camera.name;
  71409. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71410. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71411. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71412. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71413. });
  71414. }
  71415. }
  71416. }
  71417. };
  71418. /**
  71419. * Disables the effect on the given cameras
  71420. * @param cameras The camera to disable.
  71421. */
  71422. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71423. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71424. if (!cams) {
  71425. return;
  71426. }
  71427. for (var i = 0; i < cams.length; i++) {
  71428. var camera = cams[i];
  71429. var cameraName = camera.name;
  71430. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71431. camera.detachPostProcess(postProcess);
  71432. });
  71433. }
  71434. };
  71435. /**
  71436. * Gets a list of the post processes contained in the effect.
  71437. * @param camera The camera to get the post processes on.
  71438. * @returns The list of the post processes in the effect.
  71439. */
  71440. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71441. if (this._singleInstance) {
  71442. return this._postProcesses[0];
  71443. }
  71444. else {
  71445. if (!camera) {
  71446. return null;
  71447. }
  71448. return this._postProcesses[camera.name];
  71449. }
  71450. };
  71451. return PostProcessRenderEffect;
  71452. }());
  71453. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71454. })(BABYLON || (BABYLON = {}));
  71455. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71456. var BABYLON;
  71457. (function (BABYLON) {
  71458. var PostProcessRenderPipeline = /** @class */ (function () {
  71459. function PostProcessRenderPipeline(engine, name) {
  71460. this.engine = engine;
  71461. this._name = name;
  71462. this._renderEffects = {};
  71463. this._renderEffectsForIsolatedPass = new Array();
  71464. this._cameras = [];
  71465. }
  71466. PostProcessRenderPipeline.prototype.getClassName = function () {
  71467. return "PostProcessRenderPipeline";
  71468. };
  71469. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71470. get: function () {
  71471. for (var renderEffectName in this._renderEffects) {
  71472. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71473. if (!this._renderEffects[renderEffectName].isSupported) {
  71474. return false;
  71475. }
  71476. }
  71477. }
  71478. return true;
  71479. },
  71480. enumerable: true,
  71481. configurable: true
  71482. });
  71483. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71484. this._renderEffects[renderEffect._name] = renderEffect;
  71485. };
  71486. // private
  71487. PostProcessRenderPipeline.prototype._rebuild = function () {
  71488. };
  71489. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71490. var renderEffects = this._renderEffects[renderEffectName];
  71491. if (!renderEffects) {
  71492. return;
  71493. }
  71494. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71495. };
  71496. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71497. var renderEffects = this._renderEffects[renderEffectName];
  71498. if (!renderEffects) {
  71499. return;
  71500. }
  71501. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71502. };
  71503. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71504. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71505. if (!cams) {
  71506. return;
  71507. }
  71508. var indicesToDelete = [];
  71509. var i;
  71510. for (i = 0; i < cams.length; i++) {
  71511. var camera = cams[i];
  71512. var cameraName = camera.name;
  71513. if (this._cameras.indexOf(camera) === -1) {
  71514. this._cameras[cameraName] = camera;
  71515. }
  71516. else if (unique) {
  71517. indicesToDelete.push(i);
  71518. }
  71519. }
  71520. for (i = 0; i < indicesToDelete.length; i++) {
  71521. cameras.splice(indicesToDelete[i], 1);
  71522. }
  71523. for (var renderEffectName in this._renderEffects) {
  71524. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71525. this._renderEffects[renderEffectName]._attachCameras(cams);
  71526. }
  71527. }
  71528. };
  71529. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71530. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71531. if (!cams) {
  71532. return;
  71533. }
  71534. for (var renderEffectName in this._renderEffects) {
  71535. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71536. this._renderEffects[renderEffectName]._detachCameras(cams);
  71537. }
  71538. }
  71539. for (var i = 0; i < cams.length; i++) {
  71540. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71541. }
  71542. };
  71543. PostProcessRenderPipeline.prototype._update = function () {
  71544. for (var renderEffectName in this._renderEffects) {
  71545. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71546. this._renderEffects[renderEffectName]._update();
  71547. }
  71548. }
  71549. for (var i = 0; i < this._cameras.length; i++) {
  71550. var cameraName = this._cameras[i].name;
  71551. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71552. this._renderEffectsForIsolatedPass[cameraName]._update();
  71553. }
  71554. }
  71555. };
  71556. PostProcessRenderPipeline.prototype._reset = function () {
  71557. this._renderEffects = {};
  71558. this._renderEffectsForIsolatedPass = new Array();
  71559. };
  71560. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71561. // 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)
  71562. var effectKeys = Object.keys(this._renderEffects);
  71563. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71564. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71565. if (postProcesses) {
  71566. postProcesses[0].samples = sampleCount;
  71567. return true;
  71568. }
  71569. }
  71570. return false;
  71571. };
  71572. PostProcessRenderPipeline.prototype.dispose = function () {
  71573. // Must be implemented by children
  71574. };
  71575. __decorate([
  71576. BABYLON.serialize()
  71577. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71578. return PostProcessRenderPipeline;
  71579. }());
  71580. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71581. })(BABYLON || (BABYLON = {}));
  71582. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71583. var BABYLON;
  71584. (function (BABYLON) {
  71585. /**
  71586. * This represents a depth renderer in Babylon.
  71587. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71588. */
  71589. var DepthRenderer = /** @class */ (function () {
  71590. /**
  71591. * Instantiates a depth renderer
  71592. * @param scene The scene the renderer belongs to
  71593. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71594. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71595. */
  71596. function DepthRenderer(scene, type, camera) {
  71597. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71598. if (camera === void 0) { camera = null; }
  71599. var _this = this;
  71600. this._scene = scene;
  71601. this._camera = camera;
  71602. var engine = scene.getEngine();
  71603. // Render target
  71604. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71605. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71606. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71607. this._depthMap.refreshRate = 1;
  71608. this._depthMap.renderParticles = false;
  71609. this._depthMap.renderList = null;
  71610. // Camera to get depth map from to support multiple concurrent cameras
  71611. this._depthMap.activeCamera = this._camera;
  71612. this._depthMap.ignoreCameraViewport = true;
  71613. this._depthMap.useCameraPostProcesses = false;
  71614. // set default depth value to 1.0 (far away)
  71615. this._depthMap.onClearObservable.add(function (engine) {
  71616. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71617. });
  71618. // Custom render function
  71619. var renderSubMesh = function (subMesh) {
  71620. var mesh = subMesh.getRenderingMesh();
  71621. var scene = _this._scene;
  71622. var engine = scene.getEngine();
  71623. var material = subMesh.getMaterial();
  71624. if (!material) {
  71625. return;
  71626. }
  71627. // Culling and reverse (right handed system)
  71628. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71629. // Managing instances
  71630. var batch = mesh._getInstancesRenderList(subMesh._id);
  71631. if (batch.mustReturn) {
  71632. return;
  71633. }
  71634. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71635. var camera = _this._camera || scene.activeCamera;
  71636. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71637. engine.enableEffect(_this._effect);
  71638. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71639. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71640. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71641. // Alpha test
  71642. if (material && material.needAlphaTesting()) {
  71643. var alphaTexture = material.getAlphaTestTexture();
  71644. if (alphaTexture) {
  71645. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71646. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71647. }
  71648. }
  71649. // Bones
  71650. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71651. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71652. }
  71653. // Draw
  71654. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71655. }
  71656. };
  71657. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71658. var index;
  71659. if (depthOnlySubMeshes.length) {
  71660. engine.setColorWrite(false);
  71661. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71662. renderSubMesh(depthOnlySubMeshes.data[index]);
  71663. }
  71664. engine.setColorWrite(true);
  71665. }
  71666. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71667. renderSubMesh(opaqueSubMeshes.data[index]);
  71668. }
  71669. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71670. renderSubMesh(alphaTestSubMeshes.data[index]);
  71671. }
  71672. };
  71673. }
  71674. /**
  71675. * Creates the depth rendering effect and checks if the effect is ready.
  71676. * @param subMesh The submesh to be used to render the depth map of
  71677. * @param useInstances If multiple world instances should be used
  71678. * @returns if the depth renderer is ready to render the depth map
  71679. */
  71680. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71681. var material = subMesh.getMaterial();
  71682. if (material.disableDepthWrite) {
  71683. return false;
  71684. }
  71685. var defines = [];
  71686. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71687. var mesh = subMesh.getMesh();
  71688. // Alpha test
  71689. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71690. defines.push("#define ALPHATEST");
  71691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71692. attribs.push(BABYLON.VertexBuffer.UVKind);
  71693. defines.push("#define UV1");
  71694. }
  71695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71696. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71697. defines.push("#define UV2");
  71698. }
  71699. }
  71700. // Bones
  71701. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71704. if (mesh.numBoneInfluencers > 4) {
  71705. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71706. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71707. }
  71708. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71709. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71710. }
  71711. else {
  71712. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71713. }
  71714. // Instances
  71715. if (useInstances) {
  71716. defines.push("#define INSTANCES");
  71717. attribs.push("world0");
  71718. attribs.push("world1");
  71719. attribs.push("world2");
  71720. attribs.push("world3");
  71721. }
  71722. // Get correct effect
  71723. var join = defines.join("\n");
  71724. if (this._cachedDefines !== join) {
  71725. this._cachedDefines = join;
  71726. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71727. }
  71728. return this._effect.isReady();
  71729. };
  71730. /**
  71731. * Gets the texture which the depth map will be written to.
  71732. * @returns The depth map texture
  71733. */
  71734. DepthRenderer.prototype.getDepthMap = function () {
  71735. return this._depthMap;
  71736. };
  71737. /**
  71738. * Disposes of the depth renderer.
  71739. */
  71740. DepthRenderer.prototype.dispose = function () {
  71741. this._depthMap.dispose();
  71742. };
  71743. return DepthRenderer;
  71744. }());
  71745. BABYLON.DepthRenderer = DepthRenderer;
  71746. })(BABYLON || (BABYLON = {}));
  71747. //# sourceMappingURL=babylon.depthRenderer.js.map
  71748. var BABYLON;
  71749. (function (BABYLON) {
  71750. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71751. __extends(SSAORenderingPipeline, _super);
  71752. /**
  71753. * @constructor
  71754. * @param {string} name - The rendering pipeline name
  71755. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71756. * @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 }
  71757. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71758. */
  71759. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71760. var _this = _super.call(this, scene.getEngine(), name) || this;
  71761. // Members
  71762. /**
  71763. * The PassPostProcess id in the pipeline that contains the original scene color
  71764. */
  71765. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71766. /**
  71767. * The SSAO PostProcess id in the pipeline
  71768. */
  71769. _this.SSAORenderEffect = "SSAORenderEffect";
  71770. /**
  71771. * The horizontal blur PostProcess id in the pipeline
  71772. */
  71773. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71774. /**
  71775. * The vertical blur PostProcess id in the pipeline
  71776. */
  71777. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71778. /**
  71779. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71780. */
  71781. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71782. /**
  71783. * The output strength of the SSAO post-process. Default value is 1.0.
  71784. */
  71785. _this.totalStrength = 1.0;
  71786. /**
  71787. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71788. */
  71789. _this.radius = 0.0001;
  71790. /**
  71791. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71792. * Must not be equal to fallOff and superior to fallOff.
  71793. * Default value is 0.975
  71794. */
  71795. _this.area = 0.0075;
  71796. /**
  71797. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71798. * Must not be equal to area and inferior to area.
  71799. * Default value is 0.0
  71800. */
  71801. _this.fallOff = 0.000001;
  71802. /**
  71803. * The base color of the SSAO post-process
  71804. * The final result is "base + ssao" between [0, 1]
  71805. */
  71806. _this.base = 0.5;
  71807. _this._firstUpdate = true;
  71808. _this._scene = scene;
  71809. // Set up assets
  71810. _this._createRandomTexture();
  71811. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71812. var ssaoRatio = ratio.ssaoRatio || ratio;
  71813. var combineRatio = ratio.combineRatio || ratio;
  71814. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71815. _this._createSSAOPostProcess(ssaoRatio);
  71816. _this._createBlurPostProcess(ssaoRatio);
  71817. _this._createSSAOCombinePostProcess(combineRatio);
  71818. // Set up pipeline
  71819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71821. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71822. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71823. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71824. // Finish
  71825. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71826. if (cameras)
  71827. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71828. return _this;
  71829. }
  71830. // Public Methods
  71831. /**
  71832. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71833. */
  71834. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71835. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71836. for (var i = 0; i < this._scene.cameras.length; i++) {
  71837. var camera = this._scene.cameras[i];
  71838. this._originalColorPostProcess.dispose(camera);
  71839. this._ssaoPostProcess.dispose(camera);
  71840. this._blurHPostProcess.dispose(camera);
  71841. this._blurVPostProcess.dispose(camera);
  71842. this._ssaoCombinePostProcess.dispose(camera);
  71843. }
  71844. this._randomTexture.dispose();
  71845. if (disableDepthRender)
  71846. this._scene.disableDepthRenderer();
  71847. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71848. _super.prototype.dispose.call(this);
  71849. };
  71850. // Private Methods
  71851. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71852. var _this = this;
  71853. var size = 16;
  71854. 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);
  71855. 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);
  71856. this._blurHPostProcess.onActivateObservable.add(function () {
  71857. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71858. _this._blurHPostProcess.kernel = size * dw;
  71859. });
  71860. this._blurVPostProcess.onActivateObservable.add(function () {
  71861. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71862. _this._blurVPostProcess.kernel = size * dw;
  71863. });
  71864. };
  71865. SSAORenderingPipeline.prototype._rebuild = function () {
  71866. this._firstUpdate = true;
  71867. _super.prototype._rebuild.call(this);
  71868. };
  71869. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71870. var _this = this;
  71871. var numSamples = 16;
  71872. var sampleSphere = [
  71873. 0.5381, 0.1856, -0.4319,
  71874. 0.1379, 0.2486, 0.4430,
  71875. 0.3371, 0.5679, -0.0057,
  71876. -0.6999, -0.0451, -0.0019,
  71877. 0.0689, -0.1598, -0.8547,
  71878. 0.0560, 0.0069, -0.1843,
  71879. -0.0146, 0.1402, 0.0762,
  71880. 0.0100, -0.1924, -0.0344,
  71881. -0.3577, -0.5301, -0.4358,
  71882. -0.3169, 0.1063, 0.0158,
  71883. 0.0103, -0.5869, 0.0046,
  71884. -0.0897, -0.4940, 0.3287,
  71885. 0.7119, -0.0154, -0.0918,
  71886. -0.0533, 0.0596, -0.5411,
  71887. 0.0352, -0.0631, 0.5460,
  71888. -0.4776, 0.2847, -0.0271
  71889. ];
  71890. var samplesFactor = 1.0 / numSamples;
  71891. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71892. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71893. "area", "fallOff", "base", "range", "viewport"
  71894. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71895. this._ssaoPostProcess.onApply = function (effect) {
  71896. if (_this._firstUpdate) {
  71897. effect.setArray3("sampleSphere", sampleSphere);
  71898. effect.setFloat("samplesFactor", samplesFactor);
  71899. effect.setFloat("randTextureTiles", 4.0);
  71900. }
  71901. effect.setFloat("totalStrength", _this.totalStrength);
  71902. effect.setFloat("radius", _this.radius);
  71903. effect.setFloat("area", _this.area);
  71904. effect.setFloat("fallOff", _this.fallOff);
  71905. effect.setFloat("base", _this.base);
  71906. effect.setTexture("textureSampler", _this._depthTexture);
  71907. effect.setTexture("randomSampler", _this._randomTexture);
  71908. };
  71909. };
  71910. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71911. var _this = this;
  71912. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71913. this._ssaoCombinePostProcess.onApply = function (effect) {
  71914. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71915. };
  71916. };
  71917. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71918. var size = 512;
  71919. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71920. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71921. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71922. var context = this._randomTexture.getContext();
  71923. var rand = function (min, max) {
  71924. return Math.random() * (max - min) + min;
  71925. };
  71926. var randVector = BABYLON.Vector3.Zero();
  71927. for (var x = 0; x < size; x++) {
  71928. for (var y = 0; y < size; y++) {
  71929. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71930. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71931. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71932. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71933. context.fillRect(x, y, 1, 1);
  71934. }
  71935. }
  71936. this._randomTexture.update(false);
  71937. };
  71938. __decorate([
  71939. BABYLON.serialize()
  71940. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71941. __decorate([
  71942. BABYLON.serialize()
  71943. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71944. __decorate([
  71945. BABYLON.serialize()
  71946. ], SSAORenderingPipeline.prototype, "area", void 0);
  71947. __decorate([
  71948. BABYLON.serialize()
  71949. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71950. __decorate([
  71951. BABYLON.serialize()
  71952. ], SSAORenderingPipeline.prototype, "base", void 0);
  71953. return SSAORenderingPipeline;
  71954. }(BABYLON.PostProcessRenderPipeline));
  71955. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71956. })(BABYLON || (BABYLON = {}));
  71957. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71958. var BABYLON;
  71959. (function (BABYLON) {
  71960. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71961. __extends(SSAO2RenderingPipeline, _super);
  71962. /**
  71963. * @constructor
  71964. * @param {string} name - The rendering pipeline name
  71965. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71966. * @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 }
  71967. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71968. */
  71969. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71970. var _this = _super.call(this, scene.getEngine(), name) || this;
  71971. // Members
  71972. /**
  71973. * The PassPostProcess id in the pipeline that contains the original scene color
  71974. */
  71975. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71976. /**
  71977. * The SSAO PostProcess id in the pipeline
  71978. */
  71979. _this.SSAORenderEffect = "SSAORenderEffect";
  71980. /**
  71981. * The horizontal blur PostProcess id in the pipeline
  71982. */
  71983. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71984. /**
  71985. * The vertical blur PostProcess id in the pipeline
  71986. */
  71987. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71988. /**
  71989. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71990. */
  71991. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71992. /**
  71993. * The output strength of the SSAO post-process. Default value is 1.0.
  71994. */
  71995. _this.totalStrength = 1.0;
  71996. /**
  71997. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71998. */
  71999. _this.maxZ = 100.0;
  72000. /**
  72001. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72002. */
  72003. _this.minZAspect = 0.2;
  72004. /**
  72005. * Number of samples used for the SSAO calculations. Default value is 8
  72006. */
  72007. _this._samples = 8;
  72008. /**
  72009. * Are we using bilateral blur ?
  72010. */
  72011. _this._expensiveBlur = true;
  72012. /**
  72013. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72014. */
  72015. _this.radius = 2.0;
  72016. /**
  72017. * The base color of the SSAO post-process
  72018. * The final result is "base + ssao" between [0, 1]
  72019. */
  72020. _this.base = 0.1;
  72021. _this._firstUpdate = true;
  72022. _this._scene = scene;
  72023. if (!_this.isSupported) {
  72024. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72025. return _this;
  72026. }
  72027. var ssaoRatio = ratio.ssaoRatio || ratio;
  72028. var blurRatio = ratio.blurRatio || ratio;
  72029. // Set up assets
  72030. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72031. _this._createRandomTexture();
  72032. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72033. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72034. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72035. _this._createSSAOPostProcess(1.0);
  72036. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72037. _this._createSSAOCombinePostProcess(blurRatio);
  72038. // Set up pipeline
  72039. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72040. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72041. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72042. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72043. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72044. // Finish
  72045. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72046. if (cameras)
  72047. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72048. return _this;
  72049. }
  72050. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72051. get: function () {
  72052. return this._samples;
  72053. },
  72054. set: function (n) {
  72055. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72056. this._samples = n;
  72057. this._sampleSphere = this._generateHemisphere();
  72058. this._firstUpdate = true;
  72059. },
  72060. enumerable: true,
  72061. configurable: true
  72062. });
  72063. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72064. get: function () {
  72065. return this._expensiveBlur;
  72066. },
  72067. set: function (b) {
  72068. 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"]);
  72069. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72070. this._expensiveBlur = b;
  72071. this._firstUpdate = true;
  72072. },
  72073. enumerable: true,
  72074. configurable: true
  72075. });
  72076. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72077. /**
  72078. * Support test.
  72079. */
  72080. get: function () {
  72081. var engine = BABYLON.Engine.LastCreatedEngine;
  72082. if (!engine) {
  72083. return false;
  72084. }
  72085. return engine.getCaps().drawBuffersExtension;
  72086. },
  72087. enumerable: true,
  72088. configurable: true
  72089. });
  72090. // Public Methods
  72091. /**
  72092. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72093. */
  72094. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72095. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72096. for (var i = 0; i < this._scene.cameras.length; i++) {
  72097. var camera = this._scene.cameras[i];
  72098. this._originalColorPostProcess.dispose(camera);
  72099. this._ssaoPostProcess.dispose(camera);
  72100. this._blurHPostProcess.dispose(camera);
  72101. this._blurVPostProcess.dispose(camera);
  72102. this._ssaoCombinePostProcess.dispose(camera);
  72103. }
  72104. this._randomTexture.dispose();
  72105. if (disableGeometryBufferRenderer)
  72106. this._scene.disableGeometryBufferRenderer();
  72107. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72108. _super.prototype.dispose.call(this);
  72109. };
  72110. // Private Methods
  72111. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72112. var _this = this;
  72113. this._samplerOffsets = [];
  72114. var expensive = this.expensiveBlur;
  72115. for (var i = -8; i < 8; i++) {
  72116. this._samplerOffsets.push(i * 2 + 0.5);
  72117. }
  72118. 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");
  72119. this._blurHPostProcess.onApply = function (effect) {
  72120. if (!_this._scene.activeCamera) {
  72121. return;
  72122. }
  72123. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72124. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72125. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72126. effect.setFloat("radius", _this.radius);
  72127. effect.setTexture("depthSampler", _this._depthTexture);
  72128. if (_this._firstUpdate) {
  72129. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72130. }
  72131. };
  72132. 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");
  72133. this._blurVPostProcess.onApply = function (effect) {
  72134. if (!_this._scene.activeCamera) {
  72135. return;
  72136. }
  72137. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72138. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72139. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72140. effect.setFloat("radius", _this.radius);
  72141. effect.setTexture("depthSampler", _this._depthTexture);
  72142. if (_this._firstUpdate) {
  72143. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72144. _this._firstUpdate = false;
  72145. }
  72146. };
  72147. };
  72148. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72149. this._firstUpdate = true;
  72150. _super.prototype._rebuild.call(this);
  72151. };
  72152. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72153. var numSamples = this.samples;
  72154. var result = [];
  72155. var vector, scale;
  72156. var rand = function (min, max) {
  72157. return Math.random() * (max - min) + min;
  72158. };
  72159. var i = 0;
  72160. while (i < numSamples) {
  72161. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72162. vector.normalize();
  72163. scale = i / numSamples;
  72164. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72165. vector.scaleInPlace(scale);
  72166. result.push(vector.x, vector.y, vector.z);
  72167. i++;
  72168. }
  72169. return result;
  72170. };
  72171. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72172. var _this = this;
  72173. var numSamples = this.samples;
  72174. this._sampleSphere = this._generateHemisphere();
  72175. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72176. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72177. "base", "range", "projection", "near", "far", "texelSize",
  72178. "xViewport", "yViewport", "maxZ", "minZAspect"
  72179. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72180. this._ssaoPostProcess.onApply = function (effect) {
  72181. if (_this._firstUpdate) {
  72182. effect.setArray3("sampleSphere", _this._sampleSphere);
  72183. effect.setFloat("randTextureTiles", 4.0);
  72184. }
  72185. if (!_this._scene.activeCamera) {
  72186. return;
  72187. }
  72188. effect.setFloat("samplesFactor", 1 / _this.samples);
  72189. effect.setFloat("totalStrength", _this.totalStrength);
  72190. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72191. effect.setFloat("radius", _this.radius);
  72192. effect.setFloat("maxZ", _this.maxZ);
  72193. effect.setFloat("minZAspect", _this.minZAspect);
  72194. effect.setFloat("base", _this.base);
  72195. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72196. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72197. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72198. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72199. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72200. effect.setTexture("textureSampler", _this._depthTexture);
  72201. effect.setTexture("normalSampler", _this._normalTexture);
  72202. effect.setTexture("randomSampler", _this._randomTexture);
  72203. };
  72204. };
  72205. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72206. var _this = this;
  72207. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72208. this._ssaoCombinePostProcess.onApply = function (effect) {
  72209. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72210. };
  72211. };
  72212. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72213. var size = 512;
  72214. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72215. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72216. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72217. var context = this._randomTexture.getContext();
  72218. var rand = function (min, max) {
  72219. return Math.random() * (max - min) + min;
  72220. };
  72221. var randVector = BABYLON.Vector3.Zero();
  72222. for (var x = 0; x < size; x++) {
  72223. for (var y = 0; y < size; y++) {
  72224. randVector.x = rand(0.0, 1.0);
  72225. randVector.y = rand(0.0, 1.0);
  72226. randVector.z = 0.0;
  72227. randVector.normalize();
  72228. randVector.scaleInPlace(255);
  72229. randVector.x = Math.floor(randVector.x);
  72230. randVector.y = Math.floor(randVector.y);
  72231. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72232. context.fillRect(x, y, 1, 1);
  72233. }
  72234. }
  72235. this._randomTexture.update(false);
  72236. };
  72237. __decorate([
  72238. BABYLON.serialize()
  72239. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72240. __decorate([
  72241. BABYLON.serialize()
  72242. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72243. __decorate([
  72244. BABYLON.serialize()
  72245. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72246. __decorate([
  72247. BABYLON.serialize("samples")
  72248. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72249. __decorate([
  72250. BABYLON.serialize("expensiveBlur")
  72251. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72252. __decorate([
  72253. BABYLON.serialize()
  72254. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72255. __decorate([
  72256. BABYLON.serialize()
  72257. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72258. return SSAO2RenderingPipeline;
  72259. }(BABYLON.PostProcessRenderPipeline));
  72260. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72261. })(BABYLON || (BABYLON = {}));
  72262. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72263. // BABYLON.JS Chromatic Aberration GLSL Shader
  72264. // Author: Olivier Guyot
  72265. // Separates very slightly R, G and B colors on the edges of the screen
  72266. // Inspired by Francois Tarlier & Martins Upitis
  72267. var BABYLON;
  72268. (function (BABYLON) {
  72269. var LensRenderingPipeline = /** @class */ (function (_super) {
  72270. __extends(LensRenderingPipeline, _super);
  72271. /**
  72272. * @constructor
  72273. *
  72274. * Effect parameters are as follow:
  72275. * {
  72276. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72277. * edge_blur: number; // from 0 to x (1 for realism)
  72278. * distortion: number; // from 0 to x (1 for realism)
  72279. * grain_amount: number; // from 0 to 1
  72280. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72281. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72282. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72283. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72284. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72285. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72286. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72287. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72288. * }
  72289. * Note: if an effect parameter is unset, effect is disabled
  72290. *
  72291. * @param {string} name - The rendering pipeline name
  72292. * @param {object} parameters - An object containing all parameters (see above)
  72293. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72294. * @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)
  72295. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72296. */
  72297. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72298. if (ratio === void 0) { ratio = 1.0; }
  72299. var _this = _super.call(this, scene.getEngine(), name) || this;
  72300. // Lens effects can be of the following:
  72301. // - chromatic aberration (slight shift of RGB colors)
  72302. // - blur on the edge of the lens
  72303. // - lens distortion
  72304. // - depth-of-field blur & highlights enhancing
  72305. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72306. // - grain effect (noise or custom texture)
  72307. // Two additional texture samplers are needed:
  72308. // - depth map (for depth-of-field)
  72309. // - grain texture
  72310. /**
  72311. * The chromatic aberration PostProcess id in the pipeline
  72312. */
  72313. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72314. /**
  72315. * The highlights enhancing PostProcess id in the pipeline
  72316. */
  72317. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72318. /**
  72319. * The depth-of-field PostProcess id in the pipeline
  72320. */
  72321. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72322. _this._scene = scene;
  72323. // Fetch texture samplers
  72324. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72325. if (parameters.grain_texture) {
  72326. _this._grainTexture = parameters.grain_texture;
  72327. }
  72328. else {
  72329. _this._createGrainTexture();
  72330. }
  72331. // save parameters
  72332. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72333. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72334. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72335. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72336. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72337. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72338. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72339. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72340. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72341. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72342. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72343. // Create effects
  72344. _this._createChromaticAberrationPostProcess(ratio);
  72345. _this._createHighlightsPostProcess(ratio);
  72346. _this._createDepthOfFieldPostProcess(ratio / 4);
  72347. // Set up pipeline
  72348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72349. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72350. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72351. if (_this._highlightsGain === -1) {
  72352. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72353. }
  72354. // Finish
  72355. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72356. if (cameras) {
  72357. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72358. }
  72359. return _this;
  72360. }
  72361. // public methods (self explanatory)
  72362. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72363. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72364. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72365. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72366. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72367. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72368. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72369. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72370. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72371. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72372. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72373. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72374. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72375. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72376. };
  72377. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72378. this._highlightsPostProcess.updateEffect();
  72379. };
  72380. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72381. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72382. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72383. this._highlightsGain = amount;
  72384. };
  72385. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72386. if (this._highlightsGain === -1) {
  72387. this._highlightsGain = 1.0;
  72388. }
  72389. this._highlightsThreshold = amount;
  72390. };
  72391. LensRenderingPipeline.prototype.disableHighlights = function () {
  72392. this._highlightsGain = -1;
  72393. };
  72394. /**
  72395. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72396. */
  72397. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72398. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72399. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72400. this._chromaticAberrationPostProcess = null;
  72401. this._highlightsPostProcess = null;
  72402. this._depthOfFieldPostProcess = null;
  72403. this._grainTexture.dispose();
  72404. if (disableDepthRender)
  72405. this._scene.disableDepthRenderer();
  72406. };
  72407. // colors shifting and distortion
  72408. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72409. var _this = this;
  72410. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72411. [], // samplers
  72412. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72413. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72414. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72415. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72416. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72417. effect.setFloat('radialIntensity', 1);
  72418. effect.setFloat2('direction', 17, 17);
  72419. effect.setFloat2('centerPosition', 0.5, 0.5);
  72420. };
  72421. };
  72422. // highlights enhancing
  72423. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72424. var _this = this;
  72425. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72426. [], // samplers
  72427. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72428. this._highlightsPostProcess.onApply = function (effect) {
  72429. effect.setFloat('gain', _this._highlightsGain);
  72430. effect.setFloat('threshold', _this._highlightsThreshold);
  72431. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72432. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72433. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72434. };
  72435. };
  72436. // colors shifting and distortion
  72437. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72438. var _this = this;
  72439. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72440. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72441. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72442. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72443. this._depthOfFieldPostProcess.onApply = function (effect) {
  72444. effect.setTexture("depthSampler", _this._depthTexture);
  72445. effect.setTexture("grainSampler", _this._grainTexture);
  72446. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72447. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72448. effect.setFloat('grain_amount', _this._grainAmount);
  72449. effect.setBool('blur_noise', _this._blurNoise);
  72450. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72451. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72452. effect.setFloat('distortion', _this._distortion);
  72453. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72454. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72455. effect.setFloat('aperture', _this._dofAperture);
  72456. effect.setFloat('darken', _this._dofDarken);
  72457. effect.setFloat('edge_blur', _this._edgeBlur);
  72458. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72459. if (_this._scene.activeCamera) {
  72460. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72461. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72462. }
  72463. };
  72464. };
  72465. // creates a black and white random noise texture, 512x512
  72466. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72467. var size = 512;
  72468. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72469. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72470. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72471. var context = this._grainTexture.getContext();
  72472. var rand = function (min, max) {
  72473. return Math.random() * (max - min) + min;
  72474. };
  72475. var value;
  72476. for (var x = 0; x < size; x++) {
  72477. for (var y = 0; y < size; y++) {
  72478. value = Math.floor(rand(0.42, 0.58) * 255);
  72479. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72480. context.fillRect(x, y, 1, 1);
  72481. }
  72482. }
  72483. this._grainTexture.update(false);
  72484. };
  72485. return LensRenderingPipeline;
  72486. }(BABYLON.PostProcessRenderPipeline));
  72487. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72488. })(BABYLON || (BABYLON = {}));
  72489. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72490. var BABYLON;
  72491. (function (BABYLON) {
  72492. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72493. __extends(StandardRenderingPipeline, _super);
  72494. /**
  72495. * @constructor
  72496. * @param {string} name - The rendering pipeline name
  72497. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72498. * @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)
  72499. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72500. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72501. */
  72502. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72503. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72504. var _this = _super.call(this, scene.getEngine(), name) || this;
  72505. _this.downSampleX4PostProcess = null;
  72506. _this.brightPassPostProcess = null;
  72507. _this.blurHPostProcesses = [];
  72508. _this.blurVPostProcesses = [];
  72509. _this.textureAdderPostProcess = null;
  72510. _this.volumetricLightPostProcess = null;
  72511. _this.volumetricLightSmoothXPostProcess = null;
  72512. _this.volumetricLightSmoothYPostProcess = null;
  72513. _this.volumetricLightMergePostProces = null;
  72514. _this.volumetricLightFinalPostProcess = null;
  72515. _this.luminancePostProcess = null;
  72516. _this.luminanceDownSamplePostProcesses = [];
  72517. _this.hdrPostProcess = null;
  72518. _this.textureAdderFinalPostProcess = null;
  72519. _this.lensFlareFinalPostProcess = null;
  72520. _this.hdrFinalPostProcess = null;
  72521. _this.lensFlarePostProcess = null;
  72522. _this.lensFlareComposePostProcess = null;
  72523. _this.motionBlurPostProcess = null;
  72524. _this.depthOfFieldPostProcess = null;
  72525. // Values
  72526. _this.brightThreshold = 1.0;
  72527. _this.blurWidth = 512.0;
  72528. _this.horizontalBlur = false;
  72529. _this.exposure = 1.0;
  72530. _this.lensTexture = null;
  72531. _this.volumetricLightCoefficient = 0.2;
  72532. _this.volumetricLightPower = 4.0;
  72533. _this.volumetricLightBlurScale = 64.0;
  72534. _this.sourceLight = null;
  72535. _this.hdrMinimumLuminance = 1.0;
  72536. _this.hdrDecreaseRate = 0.5;
  72537. _this.hdrIncreaseRate = 0.5;
  72538. _this.lensColorTexture = null;
  72539. _this.lensFlareStrength = 20.0;
  72540. _this.lensFlareGhostDispersal = 1.4;
  72541. _this.lensFlareHaloWidth = 0.7;
  72542. _this.lensFlareDistortionStrength = 16.0;
  72543. _this.lensStarTexture = null;
  72544. _this.lensFlareDirtTexture = null;
  72545. _this.depthOfFieldDistance = 10.0;
  72546. _this.depthOfFieldBlurWidth = 64.0;
  72547. _this.motionStrength = 1.0;
  72548. // IAnimatable
  72549. _this.animations = [];
  72550. _this._currentDepthOfFieldSource = null;
  72551. _this._hdrCurrentLuminance = 1.0;
  72552. // Getters and setters
  72553. _this._bloomEnabled = true;
  72554. _this._depthOfFieldEnabled = false;
  72555. _this._vlsEnabled = false;
  72556. _this._lensFlareEnabled = false;
  72557. _this._hdrEnabled = false;
  72558. _this._motionBlurEnabled = false;
  72559. _this._motionBlurSamples = 64.0;
  72560. _this._volumetricLightStepsCount = 50.0;
  72561. _this._cameras = cameras || [];
  72562. // Initialize
  72563. _this._scene = scene;
  72564. _this._basePostProcess = originalPostProcess;
  72565. _this._ratio = ratio;
  72566. // Misc
  72567. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72568. // Finish
  72569. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72570. _this._buildPipeline();
  72571. return _this;
  72572. }
  72573. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72574. get: function () {
  72575. return this._bloomEnabled;
  72576. },
  72577. set: function (enabled) {
  72578. if (this._bloomEnabled === enabled) {
  72579. return;
  72580. }
  72581. this._bloomEnabled = enabled;
  72582. this._buildPipeline();
  72583. },
  72584. enumerable: true,
  72585. configurable: true
  72586. });
  72587. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72588. get: function () {
  72589. return this._depthOfFieldEnabled;
  72590. },
  72591. set: function (enabled) {
  72592. if (this._depthOfFieldEnabled === enabled) {
  72593. return;
  72594. }
  72595. this._depthOfFieldEnabled = enabled;
  72596. this._buildPipeline();
  72597. },
  72598. enumerable: true,
  72599. configurable: true
  72600. });
  72601. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72602. get: function () {
  72603. return this._lensFlareEnabled;
  72604. },
  72605. set: function (enabled) {
  72606. if (this._lensFlareEnabled === enabled) {
  72607. return;
  72608. }
  72609. this._lensFlareEnabled = enabled;
  72610. this._buildPipeline();
  72611. },
  72612. enumerable: true,
  72613. configurable: true
  72614. });
  72615. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72616. get: function () {
  72617. return this._hdrEnabled;
  72618. },
  72619. set: function (enabled) {
  72620. if (this._hdrEnabled === enabled) {
  72621. return;
  72622. }
  72623. this._hdrEnabled = enabled;
  72624. this._buildPipeline();
  72625. },
  72626. enumerable: true,
  72627. configurable: true
  72628. });
  72629. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72630. get: function () {
  72631. return this._vlsEnabled;
  72632. },
  72633. set: function (enabled) {
  72634. if (this._vlsEnabled === enabled) {
  72635. return;
  72636. }
  72637. if (enabled) {
  72638. var geometry = this._scene.enableGeometryBufferRenderer();
  72639. if (!geometry) {
  72640. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72641. return;
  72642. }
  72643. }
  72644. this._vlsEnabled = enabled;
  72645. this._buildPipeline();
  72646. },
  72647. enumerable: true,
  72648. configurable: true
  72649. });
  72650. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72651. get: function () {
  72652. return this._motionBlurEnabled;
  72653. },
  72654. set: function (enabled) {
  72655. if (this._motionBlurEnabled === enabled) {
  72656. return;
  72657. }
  72658. this._motionBlurEnabled = enabled;
  72659. this._buildPipeline();
  72660. },
  72661. enumerable: true,
  72662. configurable: true
  72663. });
  72664. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72665. get: function () {
  72666. return this._volumetricLightStepsCount;
  72667. },
  72668. set: function (count) {
  72669. if (this.volumetricLightPostProcess) {
  72670. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72671. }
  72672. this._volumetricLightStepsCount = count;
  72673. },
  72674. enumerable: true,
  72675. configurable: true
  72676. });
  72677. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72678. get: function () {
  72679. return this._motionBlurSamples;
  72680. },
  72681. set: function (samples) {
  72682. if (this.motionBlurPostProcess) {
  72683. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72684. }
  72685. this._motionBlurSamples = samples;
  72686. },
  72687. enumerable: true,
  72688. configurable: true
  72689. });
  72690. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72691. var _this = this;
  72692. var ratio = this._ratio;
  72693. var scene = this._scene;
  72694. this._disposePostProcesses();
  72695. this._reset();
  72696. // Create pass post-process
  72697. if (!this._basePostProcess) {
  72698. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72699. this.originalPostProcess.onApply = function (effect) {
  72700. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72701. };
  72702. }
  72703. else {
  72704. this.originalPostProcess = this._basePostProcess;
  72705. }
  72706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72707. this._currentDepthOfFieldSource = this.originalPostProcess;
  72708. if (this._vlsEnabled) {
  72709. // Create volumetric light
  72710. this._createVolumetricLightPostProcess(scene, ratio);
  72711. // Create volumetric light final post-process
  72712. 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);
  72713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72714. }
  72715. if (this._bloomEnabled) {
  72716. // Create down sample X4 post-process
  72717. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72718. // Create bright pass post-process
  72719. this._createBrightPassPostProcess(scene, ratio / 2);
  72720. // Create gaussian blur post-processes (down sampling blurs)
  72721. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72722. // Create texture adder post-process
  72723. this._createTextureAdderPostProcess(scene, ratio);
  72724. // Create depth-of-field source post-process
  72725. 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);
  72726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72727. }
  72728. if (this._lensFlareEnabled) {
  72729. // Create lens flare post-process
  72730. this._createLensFlarePostProcess(scene, ratio);
  72731. // Create depth-of-field source post-process post lens-flare and disable it now
  72732. 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);
  72733. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72734. }
  72735. if (this._hdrEnabled) {
  72736. // Create luminance
  72737. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72738. // Create HDR
  72739. this._createHdrPostProcess(scene, ratio);
  72740. // Create depth-of-field source post-process post hdr and disable it now
  72741. 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);
  72742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72743. }
  72744. if (this._depthOfFieldEnabled) {
  72745. // Create gaussian blur used by depth-of-field
  72746. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72747. // Create depth-of-field post-process
  72748. this._createDepthOfFieldPostProcess(scene, ratio);
  72749. }
  72750. if (this._motionBlurEnabled) {
  72751. // Create motion blur post-process
  72752. this._createMotionBlurPostProcess(scene, ratio);
  72753. }
  72754. if (this._cameras !== null) {
  72755. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72756. }
  72757. };
  72758. // Down Sample X4 Post-Processs
  72759. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72760. var _this = this;
  72761. var downSampleX4Offsets = new Array(32);
  72762. 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);
  72763. this.downSampleX4PostProcess.onApply = function (effect) {
  72764. var id = 0;
  72765. var width = _this.downSampleX4PostProcess.width;
  72766. var height = _this.downSampleX4PostProcess.height;
  72767. for (var i = -2; i < 2; i++) {
  72768. for (var j = -2; j < 2; j++) {
  72769. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72770. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72771. id += 2;
  72772. }
  72773. }
  72774. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72775. };
  72776. // Add to pipeline
  72777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72778. };
  72779. // Brightpass Post-Process
  72780. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72781. var _this = this;
  72782. var brightOffsets = new Array(8);
  72783. 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);
  72784. this.brightPassPostProcess.onApply = function (effect) {
  72785. var sU = (1.0 / _this.brightPassPostProcess.width);
  72786. var sV = (1.0 / _this.brightPassPostProcess.height);
  72787. brightOffsets[0] = -0.5 * sU;
  72788. brightOffsets[1] = 0.5 * sV;
  72789. brightOffsets[2] = 0.5 * sU;
  72790. brightOffsets[3] = 0.5 * sV;
  72791. brightOffsets[4] = -0.5 * sU;
  72792. brightOffsets[5] = -0.5 * sV;
  72793. brightOffsets[6] = 0.5 * sU;
  72794. brightOffsets[7] = -0.5 * sV;
  72795. effect.setArray2("dsOffsets", brightOffsets);
  72796. effect.setFloat("brightThreshold", _this.brightThreshold);
  72797. };
  72798. // Add to pipeline
  72799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72800. };
  72801. // Create blur H&V post-processes
  72802. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72803. var _this = this;
  72804. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72805. var engine = scene.getEngine();
  72806. 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);
  72807. 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);
  72808. blurX.onActivateObservable.add(function () {
  72809. var dw = blurX.width / engine.getRenderWidth();
  72810. blurX.kernel = _this[blurWidthKey] * dw;
  72811. });
  72812. blurY.onActivateObservable.add(function () {
  72813. var dw = blurY.height / engine.getRenderHeight();
  72814. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72815. });
  72816. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72818. this.blurHPostProcesses.push(blurX);
  72819. this.blurVPostProcesses.push(blurY);
  72820. };
  72821. // Create texture adder post-process
  72822. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72823. var _this = this;
  72824. 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);
  72825. this.textureAdderPostProcess.onApply = function (effect) {
  72826. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72827. effect.setTexture("lensSampler", _this.lensTexture);
  72828. effect.setFloat("exposure", _this.exposure);
  72829. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72830. };
  72831. // Add to pipeline
  72832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72833. };
  72834. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72835. var _this = this;
  72836. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72837. geometryRenderer.enablePosition = true;
  72838. var geometry = geometryRenderer.getGBuffer();
  72839. // Base post-process
  72840. 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));
  72841. var depthValues = BABYLON.Vector2.Zero();
  72842. this.volumetricLightPostProcess.onApply = function (effect) {
  72843. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72844. var generator = _this.sourceLight.getShadowGenerator();
  72845. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72846. effect.setTexture("positionSampler", geometry.textures[2]);
  72847. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72848. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72849. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72850. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72851. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72852. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72853. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72854. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72855. effect.setVector2("depthValues", depthValues);
  72856. }
  72857. };
  72858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72859. // Smooth
  72860. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72861. // Merge
  72862. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72863. this.volumetricLightMergePostProces.onApply = function (effect) {
  72864. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72865. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72866. };
  72867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72868. };
  72869. // Create luminance
  72870. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72871. var _this = this;
  72872. // Create luminance
  72873. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72874. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72875. var offsets = [];
  72876. this.luminancePostProcess.onApply = function (effect) {
  72877. var sU = (1.0 / _this.luminancePostProcess.width);
  72878. var sV = (1.0 / _this.luminancePostProcess.height);
  72879. offsets[0] = -0.5 * sU;
  72880. offsets[1] = 0.5 * sV;
  72881. offsets[2] = 0.5 * sU;
  72882. offsets[3] = 0.5 * sV;
  72883. offsets[4] = -0.5 * sU;
  72884. offsets[5] = -0.5 * sV;
  72885. offsets[6] = 0.5 * sU;
  72886. offsets[7] = -0.5 * sV;
  72887. effect.setArray2("lumOffsets", offsets);
  72888. };
  72889. // Add to pipeline
  72890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72891. // Create down sample luminance
  72892. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72893. var size = Math.pow(3, i);
  72894. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72895. if (i === 0) {
  72896. defines += "#define FINAL_DOWN_SAMPLER";
  72897. }
  72898. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72899. this.luminanceDownSamplePostProcesses.push(postProcess);
  72900. }
  72901. // Create callbacks and add effects
  72902. var lastLuminance = this.luminancePostProcess;
  72903. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72904. var downSampleOffsets = new Array(18);
  72905. pp.onApply = function (effect) {
  72906. if (!lastLuminance) {
  72907. return;
  72908. }
  72909. var id = 0;
  72910. for (var x = -1; x < 2; x++) {
  72911. for (var y = -1; y < 2; y++) {
  72912. downSampleOffsets[id] = x / lastLuminance.width;
  72913. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72914. id += 2;
  72915. }
  72916. }
  72917. effect.setArray2("dsOffsets", downSampleOffsets);
  72918. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72919. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72920. lastLuminance = _this.luminancePostProcess;
  72921. }
  72922. else {
  72923. lastLuminance = pp;
  72924. }
  72925. };
  72926. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72927. pp.onAfterRender = function (effect) {
  72928. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72929. 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);
  72930. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72931. };
  72932. }
  72933. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72934. });
  72935. };
  72936. // Create HDR post-process
  72937. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72938. var _this = this;
  72939. 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);
  72940. var outputLiminance = 1;
  72941. var time = 0;
  72942. var lastTime = 0;
  72943. this.hdrPostProcess.onApply = function (effect) {
  72944. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72945. time += scene.getEngine().getDeltaTime();
  72946. if (outputLiminance < 0) {
  72947. outputLiminance = _this._hdrCurrentLuminance;
  72948. }
  72949. else {
  72950. var dt = (lastTime - time) / 1000.0;
  72951. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72952. outputLiminance += _this.hdrDecreaseRate * dt;
  72953. }
  72954. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72955. outputLiminance -= _this.hdrIncreaseRate * dt;
  72956. }
  72957. else {
  72958. outputLiminance = _this._hdrCurrentLuminance;
  72959. }
  72960. }
  72961. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72962. effect.setFloat("averageLuminance", outputLiminance);
  72963. lastTime = time;
  72964. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72965. };
  72966. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72967. };
  72968. // Create lens flare post-process
  72969. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72970. var _this = this;
  72971. 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);
  72972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72973. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72974. 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);
  72975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72976. var resolution = new BABYLON.Vector2(0, 0);
  72977. // Lens flare
  72978. this.lensFlarePostProcess.onApply = function (effect) {
  72979. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72980. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72981. effect.setFloat("strength", _this.lensFlareStrength);
  72982. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72983. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72984. // Shift
  72985. resolution.x = _this.lensFlarePostProcess.width;
  72986. resolution.y = _this.lensFlarePostProcess.height;
  72987. effect.setVector2("resolution", resolution);
  72988. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72989. };
  72990. // Compose
  72991. 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);
  72992. 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);
  72993. this.lensFlareComposePostProcess.onApply = function (effect) {
  72994. if (!_this._scene.activeCamera) {
  72995. return;
  72996. }
  72997. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72998. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72999. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73000. // Lens start rotation matrix
  73001. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73002. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73003. 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));
  73004. camRot *= 4.0;
  73005. 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);
  73006. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73007. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73008. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73009. };
  73010. };
  73011. // Create depth-of-field post-process
  73012. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73013. var _this = this;
  73014. 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);
  73015. this.depthOfFieldPostProcess.onApply = function (effect) {
  73016. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73017. effect.setTexture("depthSampler", _this._getDepthTexture());
  73018. effect.setFloat("distance", _this.depthOfFieldDistance);
  73019. };
  73020. // Add to pipeline
  73021. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73022. };
  73023. // Create motion blur post-process
  73024. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73025. var _this = this;
  73026. 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);
  73027. var motionScale = 0;
  73028. var prevViewProjection = BABYLON.Matrix.Identity();
  73029. var invViewProjection = BABYLON.Matrix.Identity();
  73030. var viewProjection = BABYLON.Matrix.Identity();
  73031. var screenSize = BABYLON.Vector2.Zero();
  73032. this.motionBlurPostProcess.onApply = function (effect) {
  73033. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73034. viewProjection.invertToRef(invViewProjection);
  73035. effect.setMatrix("inverseViewProjection", invViewProjection);
  73036. effect.setMatrix("prevViewProjection", prevViewProjection);
  73037. prevViewProjection = viewProjection;
  73038. screenSize.x = _this.motionBlurPostProcess.width;
  73039. screenSize.y = _this.motionBlurPostProcess.height;
  73040. effect.setVector2("screenSize", screenSize);
  73041. motionScale = scene.getEngine().getFps() / 60.0;
  73042. effect.setFloat("motionScale", motionScale);
  73043. effect.setFloat("motionStrength", _this.motionStrength);
  73044. effect.setTexture("depthSampler", _this._getDepthTexture());
  73045. };
  73046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73047. };
  73048. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73049. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73050. var renderer = this._scene.enableGeometryBufferRenderer();
  73051. return renderer.getGBuffer().textures[0];
  73052. }
  73053. return this._scene.enableDepthRenderer().getDepthMap();
  73054. };
  73055. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73056. for (var i = 0; i < this._cameras.length; i++) {
  73057. var camera = this._cameras[i];
  73058. if (this.originalPostProcess) {
  73059. this.originalPostProcess.dispose(camera);
  73060. }
  73061. if (this.downSampleX4PostProcess) {
  73062. this.downSampleX4PostProcess.dispose(camera);
  73063. }
  73064. if (this.brightPassPostProcess) {
  73065. this.brightPassPostProcess.dispose(camera);
  73066. }
  73067. if (this.textureAdderPostProcess) {
  73068. this.textureAdderPostProcess.dispose(camera);
  73069. }
  73070. if (this.textureAdderFinalPostProcess) {
  73071. this.textureAdderFinalPostProcess.dispose(camera);
  73072. }
  73073. if (this.volumetricLightPostProcess) {
  73074. this.volumetricLightPostProcess.dispose(camera);
  73075. }
  73076. if (this.volumetricLightSmoothXPostProcess) {
  73077. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73078. }
  73079. if (this.volumetricLightSmoothYPostProcess) {
  73080. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73081. }
  73082. if (this.volumetricLightMergePostProces) {
  73083. this.volumetricLightMergePostProces.dispose(camera);
  73084. }
  73085. if (this.volumetricLightFinalPostProcess) {
  73086. this.volumetricLightFinalPostProcess.dispose(camera);
  73087. }
  73088. if (this.lensFlarePostProcess) {
  73089. this.lensFlarePostProcess.dispose(camera);
  73090. }
  73091. if (this.lensFlareComposePostProcess) {
  73092. this.lensFlareComposePostProcess.dispose(camera);
  73093. }
  73094. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73095. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73096. }
  73097. if (this.luminancePostProcess) {
  73098. this.luminancePostProcess.dispose(camera);
  73099. }
  73100. if (this.hdrPostProcess) {
  73101. this.hdrPostProcess.dispose(camera);
  73102. }
  73103. if (this.hdrFinalPostProcess) {
  73104. this.hdrFinalPostProcess.dispose(camera);
  73105. }
  73106. if (this.depthOfFieldPostProcess) {
  73107. this.depthOfFieldPostProcess.dispose(camera);
  73108. }
  73109. if (this.motionBlurPostProcess) {
  73110. this.motionBlurPostProcess.dispose(camera);
  73111. }
  73112. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73113. this.blurHPostProcesses[j].dispose(camera);
  73114. }
  73115. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73116. this.blurVPostProcesses[j].dispose(camera);
  73117. }
  73118. }
  73119. this.originalPostProcess = null;
  73120. this.downSampleX4PostProcess = null;
  73121. this.brightPassPostProcess = null;
  73122. this.textureAdderPostProcess = null;
  73123. this.textureAdderFinalPostProcess = null;
  73124. this.volumetricLightPostProcess = null;
  73125. this.volumetricLightSmoothXPostProcess = null;
  73126. this.volumetricLightSmoothYPostProcess = null;
  73127. this.volumetricLightMergePostProces = null;
  73128. this.volumetricLightFinalPostProcess = null;
  73129. this.lensFlarePostProcess = null;
  73130. this.lensFlareComposePostProcess = null;
  73131. this.luminancePostProcess = null;
  73132. this.hdrPostProcess = null;
  73133. this.hdrFinalPostProcess = null;
  73134. this.depthOfFieldPostProcess = null;
  73135. this.motionBlurPostProcess = null;
  73136. this.luminanceDownSamplePostProcesses = [];
  73137. this.blurHPostProcesses = [];
  73138. this.blurVPostProcesses = [];
  73139. };
  73140. // Dispose
  73141. StandardRenderingPipeline.prototype.dispose = function () {
  73142. this._disposePostProcesses();
  73143. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73144. _super.prototype.dispose.call(this);
  73145. };
  73146. // Serialize rendering pipeline
  73147. StandardRenderingPipeline.prototype.serialize = function () {
  73148. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73149. serializationObject.customType = "StandardRenderingPipeline";
  73150. return serializationObject;
  73151. };
  73152. /**
  73153. * Static members
  73154. */
  73155. // Parse serialized pipeline
  73156. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73157. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73158. };
  73159. // Luminance steps
  73160. StandardRenderingPipeline.LuminanceSteps = 6;
  73161. __decorate([
  73162. BABYLON.serialize()
  73163. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73164. __decorate([
  73165. BABYLON.serialize()
  73166. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73167. __decorate([
  73168. BABYLON.serialize()
  73169. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73170. __decorate([
  73171. BABYLON.serialize()
  73172. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73173. __decorate([
  73174. BABYLON.serializeAsTexture("lensTexture")
  73175. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73176. __decorate([
  73177. BABYLON.serialize()
  73178. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73179. __decorate([
  73180. BABYLON.serialize()
  73181. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73182. __decorate([
  73183. BABYLON.serialize()
  73184. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73185. __decorate([
  73186. BABYLON.serialize()
  73187. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73188. __decorate([
  73189. BABYLON.serialize()
  73190. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73191. __decorate([
  73192. BABYLON.serialize()
  73193. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73194. __decorate([
  73195. BABYLON.serializeAsTexture("lensColorTexture")
  73196. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73197. __decorate([
  73198. BABYLON.serialize()
  73199. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73200. __decorate([
  73201. BABYLON.serialize()
  73202. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73203. __decorate([
  73204. BABYLON.serialize()
  73205. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73206. __decorate([
  73207. BABYLON.serialize()
  73208. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73209. __decorate([
  73210. BABYLON.serializeAsTexture("lensStarTexture")
  73211. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73212. __decorate([
  73213. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73214. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73215. __decorate([
  73216. BABYLON.serialize()
  73217. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73218. __decorate([
  73219. BABYLON.serialize()
  73220. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73221. __decorate([
  73222. BABYLON.serialize()
  73223. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73224. __decorate([
  73225. BABYLON.serialize()
  73226. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73227. __decorate([
  73228. BABYLON.serialize()
  73229. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73230. __decorate([
  73231. BABYLON.serialize()
  73232. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73233. __decorate([
  73234. BABYLON.serialize()
  73235. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73236. __decorate([
  73237. BABYLON.serialize()
  73238. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73239. __decorate([
  73240. BABYLON.serialize()
  73241. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73242. __decorate([
  73243. BABYLON.serialize()
  73244. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73245. __decorate([
  73246. BABYLON.serialize()
  73247. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73248. __decorate([
  73249. BABYLON.serialize()
  73250. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73251. return StandardRenderingPipeline;
  73252. }(BABYLON.PostProcessRenderPipeline));
  73253. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73254. })(BABYLON || (BABYLON = {}));
  73255. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73256. var BABYLON;
  73257. (function (BABYLON) {
  73258. var FxaaPostProcess = /** @class */ (function (_super) {
  73259. __extends(FxaaPostProcess, _super);
  73260. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73261. if (camera === void 0) { camera = null; }
  73262. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73263. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73264. _this.onApplyObservable.add(function (effect) {
  73265. var texelSize = _this.texelSize;
  73266. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73267. });
  73268. return _this;
  73269. }
  73270. return FxaaPostProcess;
  73271. }(BABYLON.PostProcess));
  73272. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73273. })(BABYLON || (BABYLON = {}));
  73274. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73275. var BABYLON;
  73276. (function (BABYLON) {
  73277. /**
  73278. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73279. */
  73280. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73281. __extends(ChromaticAberrationPostProcess, _super);
  73282. /**
  73283. * Creates a new instance ChromaticAberrationPostProcess
  73284. * @param name The name of the effect.
  73285. * @param screenWidth The width of the screen to apply the effect on.
  73286. * @param screenHeight The height of the screen to apply the effect on.
  73287. * @param options The required width/height ratio to downsize to before computing the render pass.
  73288. * @param camera The camera to apply the render pass to.
  73289. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73290. * @param engine The engine which the post process will be applied. (default: current engine)
  73291. * @param reusable If the post process can be reused on the same frame. (default: false)
  73292. * @param textureType Type of textures used when performing the post process. (default: 0)
  73293. * @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)
  73294. */
  73295. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73297. if (blockCompilation === void 0) { blockCompilation = false; }
  73298. 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;
  73299. /**
  73300. * The amount of seperation of rgb channels (default: 30)
  73301. */
  73302. _this.aberrationAmount = 30;
  73303. /**
  73304. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73305. */
  73306. _this.radialIntensity = 0;
  73307. /**
  73308. * 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))
  73309. */
  73310. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73311. /**
  73312. * 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))
  73313. */
  73314. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73315. _this.onApplyObservable.add(function (effect) {
  73316. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73317. effect.setFloat('screen_width', screenWidth);
  73318. effect.setFloat('screen_height', screenHeight);
  73319. effect.setFloat('radialIntensity', _this.radialIntensity);
  73320. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73321. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73322. });
  73323. return _this;
  73324. }
  73325. return ChromaticAberrationPostProcess;
  73326. }(BABYLON.PostProcess));
  73327. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73328. })(BABYLON || (BABYLON = {}));
  73329. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73330. var BABYLON;
  73331. (function (BABYLON) {
  73332. /**
  73333. * The GrainPostProcess adds noise to the image at mid luminance levels
  73334. */
  73335. var GrainPostProcess = /** @class */ (function (_super) {
  73336. __extends(GrainPostProcess, _super);
  73337. /**
  73338. * Creates a new instance of @see GrainPostProcess
  73339. * @param name The name of the effect.
  73340. * @param options The required width/height ratio to downsize to before computing the render pass.
  73341. * @param camera The camera to apply the render pass to.
  73342. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73343. * @param engine The engine which the post process will be applied. (default: current engine)
  73344. * @param reusable If the post process can be reused on the same frame. (default: false)
  73345. * @param textureType Type of textures used when performing the post process. (default: 0)
  73346. * @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)
  73347. */
  73348. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73350. if (blockCompilation === void 0) { blockCompilation = false; }
  73351. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73352. /**
  73353. * The intensity of the grain added (default: 30)
  73354. */
  73355. _this.intensity = 30;
  73356. /**
  73357. * If the grain should be randomized on every frame
  73358. */
  73359. _this.animated = false;
  73360. _this.onApplyObservable.add(function (effect) {
  73361. effect.setFloat('intensity', _this.intensity);
  73362. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73363. });
  73364. return _this;
  73365. }
  73366. return GrainPostProcess;
  73367. }(BABYLON.PostProcess));
  73368. BABYLON.GrainPostProcess = GrainPostProcess;
  73369. })(BABYLON || (BABYLON = {}));
  73370. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73371. var BABYLON;
  73372. (function (BABYLON) {
  73373. /**
  73374. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73375. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73376. */
  73377. var SharpenPostProcess = /** @class */ (function (_super) {
  73378. __extends(SharpenPostProcess, _super);
  73379. /**
  73380. * Creates a new instance ConvolutionPostProcess
  73381. * @param name The name of the effect.
  73382. * @param options The required width/height ratio to downsize to before computing the render pass.
  73383. * @param camera The camera to apply the render pass to.
  73384. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73385. * @param engine The engine which the post process will be applied. (default: current engine)
  73386. * @param reusable If the post process can be reused on the same frame. (default: false)
  73387. * @param textureType Type of textures used when performing the post process. (default: 0)
  73388. * @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)
  73389. */
  73390. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73392. if (blockCompilation === void 0) { blockCompilation = false; }
  73393. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73394. /**
  73395. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73396. */
  73397. _this.colorAmount = 1.0;
  73398. /**
  73399. * How much sharpness should be applied (default: 0.3)
  73400. */
  73401. _this.edgeAmount = 0.3;
  73402. _this.onApply = function (effect) {
  73403. effect.setFloat2("screenSize", _this.width, _this.height);
  73404. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73405. };
  73406. return _this;
  73407. }
  73408. return SharpenPostProcess;
  73409. }(BABYLON.PostProcess));
  73410. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73411. })(BABYLON || (BABYLON = {}));
  73412. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73413. var BABYLON;
  73414. (function (BABYLON) {
  73415. /**
  73416. * The Blur Post Process which blurs an image based on a kernel and direction.
  73417. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73418. */
  73419. var BlurPostProcess = /** @class */ (function (_super) {
  73420. __extends(BlurPostProcess, _super);
  73421. /**
  73422. * Creates a new instance BlurPostProcess
  73423. * @param name The name of the effect.
  73424. * @param direction The direction in which to blur the image.
  73425. * @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.
  73426. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73427. * @param camera The camera to apply the render pass to.
  73428. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73429. * @param engine The engine which the post process will be applied. (default: current engine)
  73430. * @param reusable If the post process can be reused on the same frame. (default: false)
  73431. * @param textureType Type of textures used when performing the post process. (default: 0)
  73432. * @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)
  73433. */
  73434. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73437. if (defines === void 0) { defines = ""; }
  73438. if (blockCompilation === void 0) { blockCompilation = false; }
  73439. 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;
  73440. _this.direction = direction;
  73441. _this.blockCompilation = blockCompilation;
  73442. _this._packedFloat = false;
  73443. _this._staticDefines = "";
  73444. _this._staticDefines = defines;
  73445. _this.onApplyObservable.add(function (effect) {
  73446. if (_this._outputTexture) {
  73447. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73448. }
  73449. else {
  73450. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73451. }
  73452. });
  73453. _this.kernel = kernel;
  73454. return _this;
  73455. }
  73456. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73457. /**
  73458. * Gets the length in pixels of the blur sample region
  73459. */
  73460. get: function () {
  73461. return this._idealKernel;
  73462. },
  73463. /**
  73464. * Sets the length in pixels of the blur sample region
  73465. */
  73466. set: function (v) {
  73467. if (this._idealKernel === v) {
  73468. return;
  73469. }
  73470. v = Math.max(v, 1);
  73471. this._idealKernel = v;
  73472. this._kernel = this._nearestBestKernel(v);
  73473. if (!this.blockCompilation) {
  73474. this._updateParameters();
  73475. }
  73476. },
  73477. enumerable: true,
  73478. configurable: true
  73479. });
  73480. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73481. /**
  73482. * Gets wether or not the blur is unpacking/repacking floats
  73483. */
  73484. get: function () {
  73485. return this._packedFloat;
  73486. },
  73487. /**
  73488. * Sets wether or not the blur needs to unpack/repack floats
  73489. */
  73490. set: function (v) {
  73491. if (this._packedFloat === v) {
  73492. return;
  73493. }
  73494. this._packedFloat = v;
  73495. if (!this.blockCompilation) {
  73496. this._updateParameters();
  73497. }
  73498. },
  73499. enumerable: true,
  73500. configurable: true
  73501. });
  73502. /**
  73503. * Updates the effect with the current post process compile time values and recompiles the shader.
  73504. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73505. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73506. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73507. * @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
  73508. * @param onCompiled Called when the shader has been compiled.
  73509. * @param onError Called if there is an error when compiling a shader.
  73510. */
  73511. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73512. if (defines === void 0) { defines = null; }
  73513. if (uniforms === void 0) { uniforms = null; }
  73514. if (samplers === void 0) { samplers = null; }
  73515. this._updateParameters(onCompiled, onError);
  73516. };
  73517. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73518. // Generate sampling offsets and weights
  73519. var N = this._kernel;
  73520. var centerIndex = (N - 1) / 2;
  73521. // Generate Gaussian sampling weights over kernel
  73522. var offsets = [];
  73523. var weights = [];
  73524. var totalWeight = 0;
  73525. for (var i = 0; i < N; i++) {
  73526. var u = i / (N - 1);
  73527. var w = this._gaussianWeight(u * 2.0 - 1);
  73528. offsets[i] = (i - centerIndex);
  73529. weights[i] = w;
  73530. totalWeight += w;
  73531. }
  73532. // Normalize weights
  73533. for (var i = 0; i < weights.length; i++) {
  73534. weights[i] /= totalWeight;
  73535. }
  73536. // Optimize: combine samples to take advantage of hardware linear sampling
  73537. // Walk from left to center, combining pairs (symmetrically)
  73538. var linearSamplingWeights = [];
  73539. var linearSamplingOffsets = [];
  73540. var linearSamplingMap = [];
  73541. for (var i = 0; i <= centerIndex; i += 2) {
  73542. var j = Math.min(i + 1, Math.floor(centerIndex));
  73543. var singleCenterSample = i === j;
  73544. if (singleCenterSample) {
  73545. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73546. }
  73547. else {
  73548. var sharedCell = j === centerIndex;
  73549. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73550. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73551. if (offsetLinear === 0) {
  73552. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73553. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73554. }
  73555. else {
  73556. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73557. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73558. }
  73559. }
  73560. }
  73561. for (var i = 0; i < linearSamplingMap.length; i++) {
  73562. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73563. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73564. }
  73565. // Replace with optimized
  73566. offsets = linearSamplingOffsets;
  73567. weights = linearSamplingWeights;
  73568. // Generate shaders
  73569. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73570. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73571. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73572. var defines = "";
  73573. defines += this._staticDefines;
  73574. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73575. if (this._staticDefines.indexOf("DOF") != -1) {
  73576. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73577. varyingCount--;
  73578. }
  73579. for (var i = 0; i < varyingCount; i++) {
  73580. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73581. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73582. }
  73583. var depCount = 0;
  73584. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73585. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73586. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73587. depCount++;
  73588. }
  73589. if (this.packedFloat) {
  73590. defines += "#define PACKEDFLOAT 1";
  73591. }
  73592. this.blockCompilation = false;
  73593. _super.prototype.updateEffect.call(this, defines, null, null, {
  73594. varyingCount: varyingCount,
  73595. depCount: depCount
  73596. }, onCompiled, onError);
  73597. };
  73598. /**
  73599. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73600. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73601. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73602. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73603. * The gaps between physical kernels are compensated for in the weighting of the samples
  73604. * @param idealKernel Ideal blur kernel.
  73605. * @return Nearest best kernel.
  73606. */
  73607. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73608. var v = Math.round(idealKernel);
  73609. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73610. var k = _a[_i];
  73611. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73612. return Math.max(k, 3);
  73613. }
  73614. }
  73615. return Math.max(v, 3);
  73616. };
  73617. /**
  73618. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73619. * @param x The point on the Gaussian distribution to sample.
  73620. * @return the value of the Gaussian function at x.
  73621. */
  73622. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73623. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73624. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73625. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73626. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73627. // truncated at around 1.3% of peak strength.
  73628. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73629. var sigma = (1 / 3);
  73630. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73631. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73632. var weight = (1.0 / denominator) * Math.exp(exponent);
  73633. return weight;
  73634. };
  73635. /**
  73636. * Generates a string that can be used as a floating point number in GLSL.
  73637. * @param x Value to print.
  73638. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73639. * @return GLSL float string.
  73640. */
  73641. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73642. if (decimalFigures === void 0) { decimalFigures = 8; }
  73643. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73644. };
  73645. return BlurPostProcess;
  73646. }(BABYLON.PostProcess));
  73647. BABYLON.BlurPostProcess = BlurPostProcess;
  73648. })(BABYLON || (BABYLON = {}));
  73649. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73650. var BABYLON;
  73651. (function (BABYLON) {
  73652. /**
  73653. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73654. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73655. * based on samples that have a large difference in distance than the center pixel.
  73656. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73657. */
  73658. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73659. __extends(DepthOfFieldBlurPostProcess, _super);
  73660. /**
  73661. * Creates a new instance CircleOfConfusionPostProcess
  73662. * @param name The name of the effect.
  73663. * @param scene The scene the effect belongs to.
  73664. * @param direction The direction the blur should be applied.
  73665. * @param kernel The size of the kernel used to blur.
  73666. * @param options The required width/height ratio to downsize to before computing the render pass.
  73667. * @param camera The camera to apply the render pass to.
  73668. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73669. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73670. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73671. * @param engine The engine which the post process will be applied. (default: current engine)
  73672. * @param reusable If the post process can be reused on the same frame. (default: false)
  73673. * @param textureType Type of textures used when performing the post process. (default: 0)
  73674. * @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)
  73675. */
  73676. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73677. if (imageToBlur === void 0) { imageToBlur = null; }
  73678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73679. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73680. if (blockCompilation === void 0) { blockCompilation = false; }
  73681. 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;
  73682. _this.direction = direction;
  73683. _this.onApplyObservable.add(function (effect) {
  73684. if (imageToBlur != null) {
  73685. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73686. }
  73687. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73688. if (scene.activeCamera) {
  73689. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73690. }
  73691. });
  73692. return _this;
  73693. }
  73694. return DepthOfFieldBlurPostProcess;
  73695. }(BABYLON.BlurPostProcess));
  73696. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73697. })(BABYLON || (BABYLON = {}));
  73698. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73699. var BABYLON;
  73700. (function (BABYLON) {
  73701. /**
  73702. * Options to be set when merging outputs from the default pipeline.
  73703. */
  73704. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73705. function DepthOfFieldMergePostProcessOptions() {
  73706. }
  73707. return DepthOfFieldMergePostProcessOptions;
  73708. }());
  73709. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73710. /**
  73711. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73712. */
  73713. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73714. __extends(DepthOfFieldMergePostProcess, _super);
  73715. /**
  73716. * Creates a new instance of DepthOfFieldMergePostProcess
  73717. * @param name The name of the effect.
  73718. * @param originalFromInput Post process which's input will be used for the merge.
  73719. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73720. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73721. * @param options The required width/height ratio to downsize to before computing the render pass.
  73722. * @param camera The camera to apply the render pass to.
  73723. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73724. * @param engine The engine which the post process will be applied. (default: current engine)
  73725. * @param reusable If the post process can be reused on the same frame. (default: false)
  73726. * @param textureType Type of textures used when performing the post process. (default: 0)
  73727. * @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)
  73728. */
  73729. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73730. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73731. if (blockCompilation === void 0) { blockCompilation = false; }
  73732. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73733. _this.blurSteps = blurSteps;
  73734. _this.onApplyObservable.add(function (effect) {
  73735. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73736. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73737. blurSteps.forEach(function (step, index) {
  73738. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73739. });
  73740. });
  73741. if (!blockCompilation) {
  73742. _this.updateEffect();
  73743. }
  73744. return _this;
  73745. }
  73746. /**
  73747. * Updates the effect with the current post process compile time values and recompiles the shader.
  73748. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73749. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73750. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73751. * @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
  73752. * @param onCompiled Called when the shader has been compiled.
  73753. * @param onError Called if there is an error when compiling a shader.
  73754. */
  73755. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73756. if (defines === void 0) { defines = null; }
  73757. if (uniforms === void 0) { uniforms = null; }
  73758. if (samplers === void 0) { samplers = null; }
  73759. if (!defines) {
  73760. defines = "";
  73761. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73762. }
  73763. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73764. };
  73765. return DepthOfFieldMergePostProcess;
  73766. }(BABYLON.PostProcess));
  73767. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73768. })(BABYLON || (BABYLON = {}));
  73769. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73770. var BABYLON;
  73771. (function (BABYLON) {
  73772. /**
  73773. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73774. */
  73775. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73776. __extends(CircleOfConfusionPostProcess, _super);
  73777. /**
  73778. * Creates a new instance CircleOfConfusionPostProcess
  73779. * @param name The name of the effect.
  73780. * @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.
  73781. * @param options The required width/height ratio to downsize to before computing the render pass.
  73782. * @param camera The camera to apply the render pass to.
  73783. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73784. * @param engine The engine which the post process will be applied. (default: current engine)
  73785. * @param reusable If the post process can be reused on the same frame. (default: false)
  73786. * @param textureType Type of textures used when performing the post process. (default: 0)
  73787. * @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)
  73788. */
  73789. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73790. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73791. if (blockCompilation === void 0) { blockCompilation = false; }
  73792. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73793. /**
  73794. * 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.
  73795. */
  73796. _this.lensSize = 50;
  73797. /**
  73798. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73799. */
  73800. _this.fStop = 1.4;
  73801. /**
  73802. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73803. */
  73804. _this.focusDistance = 2000;
  73805. /**
  73806. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73807. */
  73808. _this.focalLength = 50;
  73809. _this._depthTexture = null;
  73810. _this._depthTexture = depthTexture;
  73811. _this.onApplyObservable.add(function (effect) {
  73812. if (!_this._depthTexture) {
  73813. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73814. return;
  73815. }
  73816. effect.setTexture("depthSampler", _this._depthTexture);
  73817. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73818. var aperture = _this.lensSize / _this.fStop;
  73819. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73820. effect.setFloat('focusDistance', _this.focusDistance);
  73821. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73822. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73823. });
  73824. return _this;
  73825. }
  73826. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73827. /**
  73828. * 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.
  73829. */
  73830. set: function (value) {
  73831. this._depthTexture = value;
  73832. },
  73833. enumerable: true,
  73834. configurable: true
  73835. });
  73836. return CircleOfConfusionPostProcess;
  73837. }(BABYLON.PostProcess));
  73838. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73839. })(BABYLON || (BABYLON = {}));
  73840. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73841. var BABYLON;
  73842. (function (BABYLON) {
  73843. /**
  73844. * Specifies the level of max blur that should be applied when using the depth of field effect
  73845. */
  73846. var DepthOfFieldEffectBlurLevel;
  73847. (function (DepthOfFieldEffectBlurLevel) {
  73848. /**
  73849. * Subtle blur
  73850. */
  73851. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73852. /**
  73853. * Medium blur
  73854. */
  73855. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73856. /**
  73857. * Large blur
  73858. */
  73859. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73860. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73861. ;
  73862. /**
  73863. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73864. */
  73865. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73866. __extends(DepthOfFieldEffect, _super);
  73867. /**
  73868. * Creates a new instance DepthOfFieldEffect
  73869. * @param scene The scene the effect belongs to.
  73870. * @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.
  73871. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73872. * @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)
  73873. */
  73874. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73875. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73876. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73877. if (blockCompilation === void 0) { blockCompilation = false; }
  73878. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73879. return _this._effects;
  73880. }, true) || this;
  73881. /**
  73882. * Internal post processes in depth of field effect
  73883. */
  73884. _this._effects = [];
  73885. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73886. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73887. // 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)
  73888. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73889. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73890. _this._depthOfFieldBlurY = [];
  73891. _this._depthOfFieldBlurX = [];
  73892. var blurCount = 1;
  73893. var kernelSize = 15;
  73894. switch (blurLevel) {
  73895. case DepthOfFieldEffectBlurLevel.High: {
  73896. blurCount = 3;
  73897. kernelSize = 51;
  73898. break;
  73899. }
  73900. case DepthOfFieldEffectBlurLevel.Medium: {
  73901. blurCount = 2;
  73902. kernelSize = 31;
  73903. break;
  73904. }
  73905. default: {
  73906. kernelSize = 15;
  73907. blurCount = 1;
  73908. break;
  73909. }
  73910. }
  73911. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73912. var ratio = 1.0;
  73913. for (var i = 0; i < blurCount; i++) {
  73914. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73915. blurY.autoClear = false;
  73916. ratio = 0.75 / Math.pow(2, i);
  73917. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73918. blurX.autoClear = false;
  73919. _this._depthOfFieldBlurY.push(blurY);
  73920. _this._depthOfFieldBlurX.push(blurX);
  73921. }
  73922. // Set all post processes on the effect.
  73923. _this._effects = [_this._circleOfConfusion];
  73924. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73925. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73926. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73927. }
  73928. // Merge blurred images with original image based on circleOfConfusion
  73929. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73930. _this._dofMerge.autoClear = false;
  73931. _this._effects.push(_this._dofMerge);
  73932. return _this;
  73933. }
  73934. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73935. get: function () {
  73936. return this._circleOfConfusion.focalLength;
  73937. },
  73938. /**
  73939. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  73940. */
  73941. set: function (value) {
  73942. this._circleOfConfusion.focalLength = value;
  73943. },
  73944. enumerable: true,
  73945. configurable: true
  73946. });
  73947. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73948. get: function () {
  73949. return this._circleOfConfusion.fStop;
  73950. },
  73951. /**
  73952. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73953. */
  73954. set: function (value) {
  73955. this._circleOfConfusion.fStop = value;
  73956. },
  73957. enumerable: true,
  73958. configurable: true
  73959. });
  73960. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73961. get: function () {
  73962. return this._circleOfConfusion.focusDistance;
  73963. },
  73964. /**
  73965. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73966. */
  73967. set: function (value) {
  73968. this._circleOfConfusion.focusDistance = value;
  73969. },
  73970. enumerable: true,
  73971. configurable: true
  73972. });
  73973. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73974. get: function () {
  73975. return this._circleOfConfusion.lensSize;
  73976. },
  73977. /**
  73978. * 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.
  73979. */
  73980. set: function (value) {
  73981. this._circleOfConfusion.lensSize = value;
  73982. },
  73983. enumerable: true,
  73984. configurable: true
  73985. });
  73986. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73987. /**
  73988. * 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.
  73989. */
  73990. set: function (value) {
  73991. this._circleOfConfusion.depthTexture = value;
  73992. },
  73993. enumerable: true,
  73994. configurable: true
  73995. });
  73996. /**
  73997. * Disposes each of the internal effects for a given camera.
  73998. * @param camera The camera to dispose the effect on.
  73999. */
  74000. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74001. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74002. this._effects[effectIndex].dispose(camera);
  74003. }
  74004. };
  74005. /**
  74006. * Internal
  74007. */
  74008. DepthOfFieldEffect.prototype._updateEffects = function () {
  74009. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74010. this._effects[effectIndex].updateEffect();
  74011. }
  74012. };
  74013. /**
  74014. * Internal
  74015. * @returns if all the contained post processes are ready.
  74016. */
  74017. DepthOfFieldEffect.prototype._isReady = function () {
  74018. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74019. if (!this._effects[effectIndex].isReady()) {
  74020. return false;
  74021. }
  74022. }
  74023. return true;
  74024. };
  74025. return DepthOfFieldEffect;
  74026. }(BABYLON.PostProcessRenderEffect));
  74027. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74028. })(BABYLON || (BABYLON = {}));
  74029. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74030. var BABYLON;
  74031. (function (BABYLON) {
  74032. /**
  74033. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74034. */
  74035. var BloomMergePostProcess = /** @class */ (function (_super) {
  74036. __extends(BloomMergePostProcess, _super);
  74037. /**
  74038. * Creates a new instance of @see BloomMergePostProcess
  74039. * @param name The name of the effect.
  74040. * @param originalFromInput Post process which's input will be used for the merge.
  74041. * @param blurred Blurred highlights post process which's output will be used.
  74042. * @param weight Weight of the bloom to be added to the original input.
  74043. * @param options The required width/height ratio to downsize to before computing the render pass.
  74044. * @param camera The camera to apply the render pass to.
  74045. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74046. * @param engine The engine which the post process will be applied. (default: current engine)
  74047. * @param reusable If the post process can be reused on the same frame. (default: false)
  74048. * @param textureType Type of textures used when performing the post process. (default: 0)
  74049. * @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)
  74050. */
  74051. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74052. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74053. if (blockCompilation === void 0) { blockCompilation = false; }
  74054. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74055. _this.weight = weight;
  74056. _this.onApplyObservable.add(function (effect) {
  74057. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74058. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74059. effect.setFloat("bloomWeight", _this.weight);
  74060. });
  74061. if (!blockCompilation) {
  74062. _this.updateEffect();
  74063. }
  74064. return _this;
  74065. }
  74066. return BloomMergePostProcess;
  74067. }(BABYLON.PostProcess));
  74068. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74069. })(BABYLON || (BABYLON = {}));
  74070. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74071. var BABYLON;
  74072. (function (BABYLON) {
  74073. /**
  74074. * 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.
  74075. */
  74076. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74077. __extends(ExtractHighlightsPostProcess, _super);
  74078. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74079. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74080. if (blockCompilation === void 0) { blockCompilation = false; }
  74081. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74082. /**
  74083. * The luminance threshold, pixels below this value will be set to black.
  74084. */
  74085. _this.threshold = 0.9;
  74086. /**
  74087. * Internal
  74088. */
  74089. _this._exposure = 1;
  74090. /**
  74091. * Post process which has the input texture to be used when performing highlight extraction
  74092. */
  74093. _this._inputPostProcess = null;
  74094. _this.onApplyObservable.add(function (effect) {
  74095. if (_this._inputPostProcess) {
  74096. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74097. }
  74098. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74099. effect.setFloat('exposure', _this._exposure);
  74100. });
  74101. return _this;
  74102. }
  74103. return ExtractHighlightsPostProcess;
  74104. }(BABYLON.PostProcess));
  74105. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74106. })(BABYLON || (BABYLON = {}));
  74107. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74108. var BABYLON;
  74109. (function (BABYLON) {
  74110. /**
  74111. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74112. */
  74113. var BloomEffect = /** @class */ (function (_super) {
  74114. __extends(BloomEffect, _super);
  74115. /**
  74116. * Creates a new instance of @see BloomEffect
  74117. * @param scene The scene the effect belongs to.
  74118. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74119. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74120. * @param bloomWeight The the strength of bloom.
  74121. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74122. * @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)
  74123. */
  74124. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74125. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74126. if (blockCompilation === void 0) { blockCompilation = false; }
  74127. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74128. return _this._effects;
  74129. }, true) || this;
  74130. _this.bloomScale = bloomScale;
  74131. /**
  74132. * Internal
  74133. */
  74134. _this._effects = [];
  74135. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74136. _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);
  74137. _this._blurX.alwaysForcePOT = true;
  74138. _this._blurX.autoClear = false;
  74139. _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);
  74140. _this._blurY.alwaysForcePOT = true;
  74141. _this._blurY.autoClear = false;
  74142. _this.kernel = bloomKernel;
  74143. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74144. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74145. _this._merge.autoClear = false;
  74146. _this._effects.push(_this._merge);
  74147. return _this;
  74148. }
  74149. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74150. /**
  74151. * The luminance threshold to find bright areas of the image to bloom.
  74152. */
  74153. get: function () {
  74154. return this._downscale.threshold;
  74155. },
  74156. set: function (value) {
  74157. this._downscale.threshold = value;
  74158. },
  74159. enumerable: true,
  74160. configurable: true
  74161. });
  74162. Object.defineProperty(BloomEffect.prototype, "weight", {
  74163. /**
  74164. * The strength of the bloom.
  74165. */
  74166. get: function () {
  74167. return this._merge.weight;
  74168. },
  74169. set: function (value) {
  74170. this._merge.weight = value;
  74171. },
  74172. enumerable: true,
  74173. configurable: true
  74174. });
  74175. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74176. /**
  74177. * Specifies the size of the bloom blur kernel, relative to the final output size
  74178. */
  74179. get: function () {
  74180. return this._blurX.kernel / this.bloomScale;
  74181. },
  74182. set: function (value) {
  74183. this._blurX.kernel = value * this.bloomScale;
  74184. this._blurY.kernel = value * this.bloomScale;
  74185. },
  74186. enumerable: true,
  74187. configurable: true
  74188. });
  74189. /**
  74190. * Disposes each of the internal effects for a given camera.
  74191. * @param camera The camera to dispose the effect on.
  74192. */
  74193. BloomEffect.prototype.disposeEffects = function (camera) {
  74194. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74195. this._effects[effectIndex].dispose(camera);
  74196. }
  74197. };
  74198. /**
  74199. * Internal
  74200. */
  74201. BloomEffect.prototype._updateEffects = function () {
  74202. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74203. this._effects[effectIndex].updateEffect();
  74204. }
  74205. };
  74206. /**
  74207. * Internal
  74208. * @returns if all the contained post processes are ready.
  74209. */
  74210. BloomEffect.prototype._isReady = function () {
  74211. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74212. if (!this._effects[effectIndex].isReady()) {
  74213. return false;
  74214. }
  74215. }
  74216. return true;
  74217. };
  74218. return BloomEffect;
  74219. }(BABYLON.PostProcessRenderEffect));
  74220. BABYLON.BloomEffect = BloomEffect;
  74221. })(BABYLON || (BABYLON = {}));
  74222. //# sourceMappingURL=babylon.bloomEffect.js.map
  74223. var BABYLON;
  74224. (function (BABYLON) {
  74225. /**
  74226. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74227. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74228. */
  74229. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74230. __extends(DefaultRenderingPipeline, _super);
  74231. /**
  74232. * @constructor
  74233. * @param {string} name - The rendering pipeline name
  74234. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74235. * @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)
  74236. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74237. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74238. */
  74239. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74240. if (automaticBuild === void 0) { automaticBuild = true; }
  74241. var _this = _super.call(this, scene.getEngine(), name) || this;
  74242. _this._originalCameras = [];
  74243. /**
  74244. * ID of the sharpen post process,
  74245. */
  74246. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74247. /**
  74248. * ID of the image processing post process;
  74249. */
  74250. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74251. /**
  74252. * ID of the Fast Approximate Anti-Aliasing post process;
  74253. */
  74254. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74255. /**
  74256. * ID of the chromatic aberration post process,
  74257. */
  74258. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74259. /**
  74260. * ID of the grain post process
  74261. */
  74262. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74263. /**
  74264. * Animations which can be used to tweak settings over a period of time
  74265. */
  74266. _this.animations = [];
  74267. _this._imageProcessingConfigurationObserver = null;
  74268. // Values
  74269. _this._sharpenEnabled = false;
  74270. _this._bloomEnabled = false;
  74271. _this._depthOfFieldEnabled = false;
  74272. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74273. _this._fxaaEnabled = false;
  74274. _this._imageProcessingEnabled = true;
  74275. _this._bloomScale = 0.5;
  74276. _this._chromaticAberrationEnabled = false;
  74277. _this._grainEnabled = false;
  74278. _this._buildAllowed = true;
  74279. _this._resizeObserver = null;
  74280. _this._hardwareScaleLevel = 1.0;
  74281. _this._bloomKernel = 64;
  74282. /**
  74283. * Specifies the weight of the bloom in the final rendering
  74284. */
  74285. _this._bloomWeight = 0.15;
  74286. /**
  74287. * Specifies the luma threshold for the area that will be blurred by the bloom
  74288. */
  74289. _this._bloomThreshold = 0.9;
  74290. _this._samples = 1;
  74291. _this._hasCleared = false;
  74292. _this._prevPostProcess = null;
  74293. _this._prevPrevPostProcess = null;
  74294. _this._cameras = cameras || [];
  74295. _this._originalCameras = _this._cameras.slice();
  74296. _this._buildAllowed = automaticBuild;
  74297. // Initialize
  74298. _this._scene = scene;
  74299. var caps = _this._scene.getEngine().getCaps();
  74300. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74301. // Misc
  74302. if (_this._hdr) {
  74303. if (caps.textureHalfFloatRender) {
  74304. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74305. }
  74306. else if (caps.textureFloatRender) {
  74307. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74308. }
  74309. }
  74310. else {
  74311. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74312. }
  74313. // Attach
  74314. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74315. var engine = _this._scene.getEngine();
  74316. // Create post processes before hand so they can be modified before enabled.
  74317. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74318. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74319. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74320. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74321. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74322. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74323. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74324. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74325. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74326. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74327. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74328. _this.bloomKernel = _this.bloomKernel;
  74329. });
  74330. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74331. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74332. });
  74333. _this._buildPipeline();
  74334. return _this;
  74335. }
  74336. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74337. get: function () {
  74338. return this._sharpenEnabled;
  74339. },
  74340. /**
  74341. * Enable or disable the sharpen process from the pipeline
  74342. */
  74343. set: function (enabled) {
  74344. if (this._sharpenEnabled === enabled) {
  74345. return;
  74346. }
  74347. this._sharpenEnabled = enabled;
  74348. this._buildPipeline();
  74349. },
  74350. enumerable: true,
  74351. configurable: true
  74352. });
  74353. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74354. /**
  74355. * Specifies the size of the bloom blur kernel, relative to the final output size
  74356. */
  74357. get: function () {
  74358. return this._bloomKernel;
  74359. },
  74360. set: function (value) {
  74361. this._bloomKernel = value;
  74362. this.bloom.kernel = value / this._hardwareScaleLevel;
  74363. },
  74364. enumerable: true,
  74365. configurable: true
  74366. });
  74367. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74368. get: function () {
  74369. return this._bloomWeight;
  74370. },
  74371. /**
  74372. * The strength of the bloom.
  74373. */
  74374. set: function (value) {
  74375. if (this._bloomWeight === value) {
  74376. return;
  74377. }
  74378. this.bloom.weight = value;
  74379. this._bloomWeight = value;
  74380. },
  74381. enumerable: true,
  74382. configurable: true
  74383. });
  74384. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74385. get: function () {
  74386. return this._bloomThreshold;
  74387. },
  74388. /**
  74389. * The strength of the bloom.
  74390. */
  74391. set: function (value) {
  74392. if (this._bloomThreshold === value) {
  74393. return;
  74394. }
  74395. this.bloom.threshold = value;
  74396. this._bloomThreshold = value;
  74397. },
  74398. enumerable: true,
  74399. configurable: true
  74400. });
  74401. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74402. get: function () {
  74403. return this._bloomScale;
  74404. },
  74405. /**
  74406. * The scale of the bloom, lower value will provide better performance.
  74407. */
  74408. set: function (value) {
  74409. if (this._bloomScale === value) {
  74410. return;
  74411. }
  74412. this._bloomScale = value;
  74413. // recreate bloom and dispose old as this setting is not dynamic
  74414. this._rebuildBloom();
  74415. this._buildPipeline();
  74416. },
  74417. enumerable: true,
  74418. configurable: true
  74419. });
  74420. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74421. get: function () {
  74422. return this._bloomEnabled;
  74423. },
  74424. /**
  74425. * Enable or disable the bloom from the pipeline
  74426. */
  74427. set: function (enabled) {
  74428. if (this._bloomEnabled === enabled) {
  74429. return;
  74430. }
  74431. this._bloomEnabled = enabled;
  74432. this._buildPipeline();
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74438. // recreate bloom and dispose old as this setting is not dynamic
  74439. var oldBloom = this.bloom;
  74440. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74441. this.bloom.threshold = oldBloom.threshold;
  74442. for (var i = 0; i < this._cameras.length; i++) {
  74443. oldBloom.disposeEffects(this._cameras[i]);
  74444. }
  74445. };
  74446. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74447. /**
  74448. * If the depth of field is enabled.
  74449. */
  74450. get: function () {
  74451. return this._depthOfFieldEnabled;
  74452. },
  74453. set: function (enabled) {
  74454. if (this._depthOfFieldEnabled === enabled) {
  74455. return;
  74456. }
  74457. this._depthOfFieldEnabled = enabled;
  74458. this._buildPipeline();
  74459. },
  74460. enumerable: true,
  74461. configurable: true
  74462. });
  74463. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74464. /**
  74465. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74466. */
  74467. get: function () {
  74468. return this._depthOfFieldBlurLevel;
  74469. },
  74470. set: function (value) {
  74471. if (this._depthOfFieldBlurLevel === value) {
  74472. return;
  74473. }
  74474. this._depthOfFieldBlurLevel = value;
  74475. // recreate dof and dispose old as this setting is not dynamic
  74476. var oldDof = this.depthOfField;
  74477. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74478. this.depthOfField.focalLength = oldDof.focalLength;
  74479. this.depthOfField.focusDistance = oldDof.focusDistance;
  74480. this.depthOfField.fStop = oldDof.fStop;
  74481. this.depthOfField.lensSize = oldDof.lensSize;
  74482. for (var i = 0; i < this._cameras.length; i++) {
  74483. oldDof.disposeEffects(this._cameras[i]);
  74484. }
  74485. this._buildPipeline();
  74486. },
  74487. enumerable: true,
  74488. configurable: true
  74489. });
  74490. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74491. get: function () {
  74492. return this._fxaaEnabled;
  74493. },
  74494. /**
  74495. * If the anti aliasing is enabled.
  74496. */
  74497. set: function (enabled) {
  74498. if (this._fxaaEnabled === enabled) {
  74499. return;
  74500. }
  74501. this._fxaaEnabled = enabled;
  74502. this._buildPipeline();
  74503. },
  74504. enumerable: true,
  74505. configurable: true
  74506. });
  74507. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74508. get: function () {
  74509. return this._samples;
  74510. },
  74511. /**
  74512. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74513. */
  74514. set: function (sampleCount) {
  74515. if (this._samples === sampleCount) {
  74516. return;
  74517. }
  74518. this._samples = sampleCount;
  74519. this._buildPipeline();
  74520. },
  74521. enumerable: true,
  74522. configurable: true
  74523. });
  74524. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74525. get: function () {
  74526. return this._imageProcessingEnabled;
  74527. },
  74528. /**
  74529. * If image processing is enabled.
  74530. */
  74531. set: function (enabled) {
  74532. if (this._imageProcessingEnabled === enabled) {
  74533. return;
  74534. }
  74535. this._imageProcessingEnabled = enabled;
  74536. this._buildPipeline();
  74537. },
  74538. enumerable: true,
  74539. configurable: true
  74540. });
  74541. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74542. get: function () {
  74543. return this._chromaticAberrationEnabled;
  74544. },
  74545. /**
  74546. * Enable or disable the chromaticAberration process from the pipeline
  74547. */
  74548. set: function (enabled) {
  74549. if (this._chromaticAberrationEnabled === enabled) {
  74550. return;
  74551. }
  74552. this._chromaticAberrationEnabled = enabled;
  74553. this._buildPipeline();
  74554. },
  74555. enumerable: true,
  74556. configurable: true
  74557. });
  74558. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74559. get: function () {
  74560. return this._grainEnabled;
  74561. },
  74562. /**
  74563. * Enable or disable the grain process from the pipeline
  74564. */
  74565. set: function (enabled) {
  74566. if (this._grainEnabled === enabled) {
  74567. return;
  74568. }
  74569. this._grainEnabled = enabled;
  74570. this._buildPipeline();
  74571. },
  74572. enumerable: true,
  74573. configurable: true
  74574. });
  74575. /**
  74576. * Force the compilation of the entire pipeline.
  74577. */
  74578. DefaultRenderingPipeline.prototype.prepare = function () {
  74579. var previousState = this._buildAllowed;
  74580. this._buildAllowed = true;
  74581. this._buildPipeline();
  74582. this._buildAllowed = previousState;
  74583. };
  74584. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74585. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74586. if (this._hasCleared) {
  74587. postProcess.autoClear = false;
  74588. }
  74589. else {
  74590. postProcess.autoClear = true;
  74591. this._scene.autoClear = false;
  74592. this._hasCleared = true;
  74593. }
  74594. if (!skipTextureSharing) {
  74595. if (this._prevPrevPostProcess) {
  74596. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74597. }
  74598. else {
  74599. postProcess.useOwnOutput();
  74600. }
  74601. if (this._prevPostProcess) {
  74602. this._prevPrevPostProcess = this._prevPostProcess;
  74603. }
  74604. this._prevPostProcess = postProcess;
  74605. }
  74606. };
  74607. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74608. var _this = this;
  74609. if (!this._buildAllowed) {
  74610. return;
  74611. }
  74612. this._scene.autoClear = true;
  74613. var engine = this._scene.getEngine();
  74614. this._disposePostProcesses();
  74615. if (this._cameras !== null) {
  74616. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74617. // get back cameras to be used to reattach pipeline
  74618. this._cameras = this._originalCameras.slice();
  74619. }
  74620. this._reset();
  74621. this._prevPostProcess = null;
  74622. this._prevPrevPostProcess = null;
  74623. this._hasCleared = false;
  74624. if (this.depthOfFieldEnabled) {
  74625. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74626. this.depthOfField.depthTexture = depthTexture;
  74627. if (!this.depthOfField._isReady()) {
  74628. this.depthOfField._updateEffects();
  74629. }
  74630. this.addEffect(this.depthOfField);
  74631. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74632. }
  74633. if (this.bloomEnabled) {
  74634. if (!this.bloom._isReady()) {
  74635. this.bloom._updateEffects();
  74636. }
  74637. this.addEffect(this.bloom);
  74638. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74639. }
  74640. if (this._imageProcessingEnabled) {
  74641. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74642. if (this._hdr) {
  74643. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74644. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74645. }
  74646. else {
  74647. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74648. }
  74649. }
  74650. if (this.sharpenEnabled) {
  74651. if (!this.sharpen.isReady()) {
  74652. this.sharpen.updateEffect();
  74653. }
  74654. this.addEffect(this._sharpenEffect);
  74655. this._setAutoClearAndTextureSharing(this.sharpen);
  74656. }
  74657. if (this.grainEnabled) {
  74658. if (!this.grain.isReady()) {
  74659. this.grain.updateEffect();
  74660. }
  74661. this.addEffect(this._grainEffect);
  74662. this._setAutoClearAndTextureSharing(this.grain);
  74663. }
  74664. if (this.chromaticAberrationEnabled) {
  74665. if (!this.chromaticAberration.isReady()) {
  74666. this.chromaticAberration.updateEffect();
  74667. }
  74668. this.addEffect(this._chromaticAberrationEffect);
  74669. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74670. }
  74671. if (this.fxaaEnabled) {
  74672. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74673. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74674. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74675. }
  74676. if (this._cameras !== null) {
  74677. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74678. }
  74679. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74680. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74681. }
  74682. };
  74683. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74684. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74685. for (var i = 0; i < this._cameras.length; i++) {
  74686. var camera = this._cameras[i];
  74687. if (this.imageProcessing) {
  74688. this.imageProcessing.dispose(camera);
  74689. }
  74690. if (this.fxaa) {
  74691. this.fxaa.dispose(camera);
  74692. }
  74693. // These are created in the constructor and should not be disposed on every pipeline change
  74694. if (disposeNonRecreated) {
  74695. if (this.sharpen) {
  74696. this.sharpen.dispose(camera);
  74697. }
  74698. if (this.depthOfField) {
  74699. this.depthOfField.disposeEffects(camera);
  74700. }
  74701. if (this.bloom) {
  74702. this.bloom.disposeEffects(camera);
  74703. }
  74704. if (this.chromaticAberration) {
  74705. this.chromaticAberration.dispose(camera);
  74706. }
  74707. if (this.grain) {
  74708. this.grain.dispose(camera);
  74709. }
  74710. }
  74711. }
  74712. this.imageProcessing = null;
  74713. this.fxaa = null;
  74714. if (disposeNonRecreated) {
  74715. this.sharpen = null;
  74716. this._sharpenEffect = null;
  74717. this.depthOfField = null;
  74718. this.bloom = null;
  74719. this.chromaticAberration = null;
  74720. this._chromaticAberrationEffect = null;
  74721. this.grain = null;
  74722. this._grainEffect = null;
  74723. }
  74724. };
  74725. /**
  74726. * Dispose of the pipeline and stop all post processes
  74727. */
  74728. DefaultRenderingPipeline.prototype.dispose = function () {
  74729. this._disposePostProcesses(true);
  74730. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74731. this._scene.autoClear = true;
  74732. if (this._resizeObserver) {
  74733. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74734. this._resizeObserver = null;
  74735. }
  74736. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74737. _super.prototype.dispose.call(this);
  74738. };
  74739. /**
  74740. * Serialize the rendering pipeline (Used when exporting)
  74741. * @returns the serialized object
  74742. */
  74743. DefaultRenderingPipeline.prototype.serialize = function () {
  74744. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74745. serializationObject.customType = "DefaultRenderingPipeline";
  74746. return serializationObject;
  74747. };
  74748. /**
  74749. * Parse the serialized pipeline
  74750. * @param source Source pipeline.
  74751. * @param scene The scene to load the pipeline to.
  74752. * @param rootUrl The URL of the serialized pipeline.
  74753. * @returns An instantiated pipeline from the serialized object.
  74754. */
  74755. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74756. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74757. };
  74758. __decorate([
  74759. BABYLON.serialize()
  74760. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74761. __decorate([
  74762. BABYLON.serialize()
  74763. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74764. __decorate([
  74765. BABYLON.serialize()
  74766. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74767. __decorate([
  74768. BABYLON.serialize()
  74769. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74770. __decorate([
  74771. BABYLON.serialize()
  74772. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74773. __decorate([
  74774. BABYLON.serialize()
  74775. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74776. __decorate([
  74777. BABYLON.serialize()
  74778. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74779. __decorate([
  74780. BABYLON.serialize()
  74781. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74782. __decorate([
  74783. BABYLON.serialize()
  74784. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74785. __decorate([
  74786. BABYLON.serialize()
  74787. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74788. __decorate([
  74789. BABYLON.serialize()
  74790. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74791. __decorate([
  74792. BABYLON.serialize()
  74793. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74794. __decorate([
  74795. BABYLON.serialize()
  74796. ], DefaultRenderingPipeline.prototype, "samples", null);
  74797. __decorate([
  74798. BABYLON.serialize()
  74799. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74800. __decorate([
  74801. BABYLON.serialize()
  74802. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74803. __decorate([
  74804. BABYLON.serialize()
  74805. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74806. return DefaultRenderingPipeline;
  74807. }(BABYLON.PostProcessRenderPipeline));
  74808. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74809. })(BABYLON || (BABYLON = {}));
  74810. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74811. var BABYLON;
  74812. (function (BABYLON) {
  74813. /**
  74814. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74815. */
  74816. var GeometryBufferRenderer = /** @class */ (function () {
  74817. /**
  74818. * Creates a new G Buffer for the scene
  74819. * @param scene The scene the buffer belongs to
  74820. * @param ratio How big is the buffer related to the main canvas.
  74821. */
  74822. function GeometryBufferRenderer(scene, ratio) {
  74823. if (ratio === void 0) { ratio = 1; }
  74824. this._enablePosition = false;
  74825. this._scene = scene;
  74826. this._ratio = ratio;
  74827. // Render target
  74828. this._createRenderTargets();
  74829. }
  74830. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74831. /**
  74832. * Set the render list (meshes to be rendered) used in the G buffer.
  74833. */
  74834. set: function (meshes) {
  74835. this._multiRenderTarget.renderList = meshes;
  74836. },
  74837. enumerable: true,
  74838. configurable: true
  74839. });
  74840. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74841. /**
  74842. * Gets wether or not G buffer are supported by the running hardware.
  74843. * This requires draw buffer supports
  74844. */
  74845. get: function () {
  74846. return this._multiRenderTarget.isSupported;
  74847. },
  74848. enumerable: true,
  74849. configurable: true
  74850. });
  74851. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74852. /**
  74853. * Gets wether or not position are enabled for the G buffer.
  74854. */
  74855. get: function () {
  74856. return this._enablePosition;
  74857. },
  74858. /**
  74859. * Sets wether or not position are enabled for the G buffer.
  74860. */
  74861. set: function (enable) {
  74862. this._enablePosition = enable;
  74863. this.dispose();
  74864. this._createRenderTargets();
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74870. /**
  74871. * Gets the scene associated with the buffer.
  74872. */
  74873. get: function () {
  74874. return this._scene;
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74880. /**
  74881. * Gets the ratio used by the buffer during its creation.
  74882. * How big is the buffer related to the main canvas.
  74883. */
  74884. get: function () {
  74885. return this._ratio;
  74886. },
  74887. enumerable: true,
  74888. configurable: true
  74889. });
  74890. /**
  74891. * Checks wether everything is ready to render a submesh to the G buffer.
  74892. * @param subMesh the submesh to check readiness for
  74893. * @param useInstances is the mesh drawn using instance or not
  74894. * @returns true if ready otherwise false
  74895. */
  74896. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74897. var material = subMesh.getMaterial();
  74898. if (material && material.disableDepthWrite) {
  74899. return false;
  74900. }
  74901. var defines = [];
  74902. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74903. var mesh = subMesh.getMesh();
  74904. // Alpha test
  74905. if (material && material.needAlphaTesting()) {
  74906. defines.push("#define ALPHATEST");
  74907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74908. attribs.push(BABYLON.VertexBuffer.UVKind);
  74909. defines.push("#define UV1");
  74910. }
  74911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74912. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74913. defines.push("#define UV2");
  74914. }
  74915. }
  74916. // Buffers
  74917. if (this._enablePosition) {
  74918. defines.push("#define POSITION");
  74919. }
  74920. // Bones
  74921. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74922. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74923. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74924. if (mesh.numBoneInfluencers > 4) {
  74925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74927. }
  74928. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74929. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74930. }
  74931. else {
  74932. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74933. }
  74934. // Instances
  74935. if (useInstances) {
  74936. defines.push("#define INSTANCES");
  74937. attribs.push("world0");
  74938. attribs.push("world1");
  74939. attribs.push("world2");
  74940. attribs.push("world3");
  74941. }
  74942. // Get correct effect
  74943. var join = defines.join("\n");
  74944. if (this._cachedDefines !== join) {
  74945. this._cachedDefines = join;
  74946. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74947. }
  74948. return this._effect.isReady();
  74949. };
  74950. /**
  74951. * Gets the current underlying G Buffer.
  74952. * @returns the buffer
  74953. */
  74954. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74955. return this._multiRenderTarget;
  74956. };
  74957. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74958. /**
  74959. * Gets the number of samples used to render the buffer (anti aliasing).
  74960. */
  74961. get: function () {
  74962. return this._multiRenderTarget.samples;
  74963. },
  74964. /**
  74965. * Sets the number of samples used to render the buffer (anti aliasing).
  74966. */
  74967. set: function (value) {
  74968. this._multiRenderTarget.samples = value;
  74969. },
  74970. enumerable: true,
  74971. configurable: true
  74972. });
  74973. /**
  74974. * Disposes the renderer and frees up associated resources.
  74975. */
  74976. GeometryBufferRenderer.prototype.dispose = function () {
  74977. this.getGBuffer().dispose();
  74978. };
  74979. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74980. var _this = this;
  74981. var engine = this._scene.getEngine();
  74982. var count = this._enablePosition ? 3 : 2;
  74983. 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 });
  74984. if (!this.isSupported) {
  74985. return;
  74986. }
  74987. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74988. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74989. this._multiRenderTarget.refreshRate = 1;
  74990. this._multiRenderTarget.renderParticles = false;
  74991. this._multiRenderTarget.renderList = null;
  74992. // set default depth value to 1.0 (far away)
  74993. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74994. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74995. });
  74996. // Custom render function
  74997. var renderSubMesh = function (subMesh) {
  74998. var mesh = subMesh.getRenderingMesh();
  74999. var scene = _this._scene;
  75000. var engine = scene.getEngine();
  75001. var material = subMesh.getMaterial();
  75002. if (!material) {
  75003. return;
  75004. }
  75005. // Culling
  75006. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75007. // Managing instances
  75008. var batch = mesh._getInstancesRenderList(subMesh._id);
  75009. if (batch.mustReturn) {
  75010. return;
  75011. }
  75012. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75013. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75014. engine.enableEffect(_this._effect);
  75015. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75016. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75017. _this._effect.setMatrix("view", scene.getViewMatrix());
  75018. // Alpha test
  75019. if (material && material.needAlphaTesting()) {
  75020. var alphaTexture = material.getAlphaTestTexture();
  75021. if (alphaTexture) {
  75022. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75023. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75024. }
  75025. }
  75026. // Bones
  75027. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75028. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75029. }
  75030. // Draw
  75031. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75032. }
  75033. };
  75034. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75035. var index;
  75036. if (depthOnlySubMeshes.length) {
  75037. engine.setColorWrite(false);
  75038. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75039. renderSubMesh(depthOnlySubMeshes.data[index]);
  75040. }
  75041. engine.setColorWrite(true);
  75042. }
  75043. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75044. renderSubMesh(opaqueSubMeshes.data[index]);
  75045. }
  75046. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75047. renderSubMesh(alphaTestSubMeshes.data[index]);
  75048. }
  75049. };
  75050. };
  75051. return GeometryBufferRenderer;
  75052. }());
  75053. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75054. })(BABYLON || (BABYLON = {}));
  75055. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75056. var BABYLON;
  75057. (function (BABYLON) {
  75058. var RefractionPostProcess = /** @class */ (function (_super) {
  75059. __extends(RefractionPostProcess, _super);
  75060. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75061. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75062. _this.color = color;
  75063. _this.depth = depth;
  75064. _this.colorLevel = colorLevel;
  75065. _this._ownRefractionTexture = true;
  75066. _this.onActivateObservable.add(function (cam) {
  75067. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75068. });
  75069. _this.onApplyObservable.add(function (effect) {
  75070. effect.setColor3("baseColor", _this.color);
  75071. effect.setFloat("depth", _this.depth);
  75072. effect.setFloat("colorLevel", _this.colorLevel);
  75073. effect.setTexture("refractionSampler", _this._refTexture);
  75074. });
  75075. return _this;
  75076. }
  75077. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75078. /**
  75079. * Gets or sets the refraction texture
  75080. * Please note that you are responsible for disposing the texture if you set it manually
  75081. */
  75082. get: function () {
  75083. return this._refTexture;
  75084. },
  75085. set: function (value) {
  75086. if (this._refTexture && this._ownRefractionTexture) {
  75087. this._refTexture.dispose();
  75088. }
  75089. this._refTexture = value;
  75090. this._ownRefractionTexture = false;
  75091. },
  75092. enumerable: true,
  75093. configurable: true
  75094. });
  75095. // Methods
  75096. RefractionPostProcess.prototype.dispose = function (camera) {
  75097. if (this._refTexture && this._ownRefractionTexture) {
  75098. this._refTexture.dispose();
  75099. this._refTexture = null;
  75100. }
  75101. _super.prototype.dispose.call(this, camera);
  75102. };
  75103. return RefractionPostProcess;
  75104. }(BABYLON.PostProcess));
  75105. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75106. })(BABYLON || (BABYLON = {}));
  75107. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75108. var BABYLON;
  75109. (function (BABYLON) {
  75110. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75111. __extends(BlackAndWhitePostProcess, _super);
  75112. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75113. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75114. _this.degree = 1;
  75115. _this.onApplyObservable.add(function (effect) {
  75116. effect.setFloat("degree", _this.degree);
  75117. });
  75118. return _this;
  75119. }
  75120. return BlackAndWhitePostProcess;
  75121. }(BABYLON.PostProcess));
  75122. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75123. })(BABYLON || (BABYLON = {}));
  75124. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75125. var BABYLON;
  75126. (function (BABYLON) {
  75127. /**
  75128. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75129. * input texture to perform effects such as edge detection or sharpening
  75130. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75131. */
  75132. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75133. __extends(ConvolutionPostProcess, _super);
  75134. /**
  75135. * Creates a new instance ConvolutionPostProcess
  75136. * @param name The name of the effect.
  75137. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75138. * @param options The required width/height ratio to downsize to before computing the render pass.
  75139. * @param camera The camera to apply the render pass to.
  75140. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75141. * @param engine The engine which the post process will be applied. (default: current engine)
  75142. * @param reusable If the post process can be reused on the same frame. (default: false)
  75143. * @param textureType Type of textures used when performing the post process. (default: 0)
  75144. */
  75145. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75147. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75148. _this.kernel = kernel;
  75149. _this.onApply = function (effect) {
  75150. effect.setFloat2("screenSize", _this.width, _this.height);
  75151. effect.setArray("kernel", _this.kernel);
  75152. };
  75153. return _this;
  75154. }
  75155. // Statics
  75156. /**
  75157. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75158. */
  75159. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75160. /**
  75161. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75162. */
  75163. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75164. /**
  75165. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75166. */
  75167. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75168. /**
  75169. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75170. */
  75171. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75172. /**
  75173. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75174. */
  75175. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75176. /**
  75177. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75178. */
  75179. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75180. return ConvolutionPostProcess;
  75181. }(BABYLON.PostProcess));
  75182. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75183. })(BABYLON || (BABYLON = {}));
  75184. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75185. var BABYLON;
  75186. (function (BABYLON) {
  75187. var FilterPostProcess = /** @class */ (function (_super) {
  75188. __extends(FilterPostProcess, _super);
  75189. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75190. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75191. _this.kernelMatrix = kernelMatrix;
  75192. _this.onApply = function (effect) {
  75193. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75194. };
  75195. return _this;
  75196. }
  75197. return FilterPostProcess;
  75198. }(BABYLON.PostProcess));
  75199. BABYLON.FilterPostProcess = FilterPostProcess;
  75200. })(BABYLON || (BABYLON = {}));
  75201. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75202. var BABYLON;
  75203. (function (BABYLON) {
  75204. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75205. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75206. __extends(VolumetricLightScatteringPostProcess, _super);
  75207. /**
  75208. * @constructor
  75209. * @param {string} name - The post-process name
  75210. * @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)
  75211. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75212. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75213. * @param {number} samples - The post-process quality, default 100
  75214. * @param {number} samplingMode - The post-process filtering mode
  75215. * @param {BABYLON.Engine} engine - The babylon engine
  75216. * @param {boolean} reusable - If the post-process is reusable
  75217. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75218. */
  75219. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75220. if (samples === void 0) { samples = 100; }
  75221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75222. 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;
  75223. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75224. /**
  75225. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75226. */
  75227. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75228. /**
  75229. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75230. */
  75231. _this.useCustomMeshPosition = false;
  75232. /**
  75233. * If the post-process should inverse the light scattering direction
  75234. */
  75235. _this.invert = true;
  75236. /**
  75237. * Array containing the excluded meshes not rendered in the internal pass
  75238. */
  75239. _this.excludedMeshes = new Array();
  75240. /**
  75241. * Controls the overall intensity of the post-process
  75242. */
  75243. _this.exposure = 0.3;
  75244. /**
  75245. * Dissipates each sample's contribution in range [0, 1]
  75246. */
  75247. _this.decay = 0.96815;
  75248. /**
  75249. * Controls the overall intensity of each sample
  75250. */
  75251. _this.weight = 0.58767;
  75252. /**
  75253. * Controls the density of each sample
  75254. */
  75255. _this.density = 0.926;
  75256. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75257. engine = scene.getEngine();
  75258. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75259. // Configure mesh
  75260. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75261. // Configure
  75262. _this._createPass(scene, ratio.passRatio || ratio);
  75263. _this.onActivate = function (camera) {
  75264. if (!_this.isSupported) {
  75265. _this.dispose(camera);
  75266. }
  75267. _this.onActivate = null;
  75268. };
  75269. _this.onApplyObservable.add(function (effect) {
  75270. _this._updateMeshScreenCoordinates(scene);
  75271. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75272. effect.setFloat("exposure", _this.exposure);
  75273. effect.setFloat("decay", _this.decay);
  75274. effect.setFloat("weight", _this.weight);
  75275. effect.setFloat("density", _this.density);
  75276. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75277. });
  75278. return _this;
  75279. }
  75280. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75281. get: function () {
  75282. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75283. return false;
  75284. },
  75285. set: function (useDiffuseColor) {
  75286. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75287. },
  75288. enumerable: true,
  75289. configurable: true
  75290. });
  75291. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75292. return "VolumetricLightScatteringPostProcess";
  75293. };
  75294. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75295. var mesh = subMesh.getMesh();
  75296. // Render this.mesh as default
  75297. if (mesh === this.mesh && mesh.material) {
  75298. return mesh.material.isReady(mesh);
  75299. }
  75300. var defines = [];
  75301. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75302. var material = subMesh.getMaterial();
  75303. // Alpha test
  75304. if (material) {
  75305. if (material.needAlphaTesting()) {
  75306. defines.push("#define ALPHATEST");
  75307. }
  75308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75309. attribs.push(BABYLON.VertexBuffer.UVKind);
  75310. defines.push("#define UV1");
  75311. }
  75312. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75313. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75314. defines.push("#define UV2");
  75315. }
  75316. }
  75317. // Bones
  75318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75321. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75322. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75323. }
  75324. else {
  75325. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75326. }
  75327. // Instances
  75328. if (useInstances) {
  75329. defines.push("#define INSTANCES");
  75330. attribs.push("world0");
  75331. attribs.push("world1");
  75332. attribs.push("world2");
  75333. attribs.push("world3");
  75334. }
  75335. // Get correct effect
  75336. var join = defines.join("\n");
  75337. if (this._cachedDefines !== join) {
  75338. this._cachedDefines = join;
  75339. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75340. }
  75341. return this._volumetricLightScatteringPass.isReady();
  75342. };
  75343. /**
  75344. * Sets the new light position for light scattering effect
  75345. * @param {BABYLON.Vector3} The new custom light position
  75346. */
  75347. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75348. this.customMeshPosition = position;
  75349. };
  75350. /**
  75351. * Returns the light position for light scattering effect
  75352. * @return {BABYLON.Vector3} The custom light position
  75353. */
  75354. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75355. return this.customMeshPosition;
  75356. };
  75357. /**
  75358. * Disposes the internal assets and detaches the post-process from the camera
  75359. */
  75360. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75361. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75362. if (rttIndex !== -1) {
  75363. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75364. }
  75365. this._volumetricLightScatteringRTT.dispose();
  75366. _super.prototype.dispose.call(this, camera);
  75367. };
  75368. /**
  75369. * Returns the render target texture used by the post-process
  75370. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75371. */
  75372. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75373. return this._volumetricLightScatteringRTT;
  75374. };
  75375. // Private methods
  75376. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75377. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75378. return true;
  75379. }
  75380. return false;
  75381. };
  75382. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75383. var _this = this;
  75384. var engine = scene.getEngine();
  75385. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75386. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75387. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75388. this._volumetricLightScatteringRTT.renderList = null;
  75389. this._volumetricLightScatteringRTT.renderParticles = false;
  75390. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75391. var camera = this.getCamera();
  75392. if (camera) {
  75393. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75394. }
  75395. else {
  75396. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75397. }
  75398. // Custom render function for submeshes
  75399. var renderSubMesh = function (subMesh) {
  75400. var mesh = subMesh.getRenderingMesh();
  75401. if (_this._meshExcluded(mesh)) {
  75402. return;
  75403. }
  75404. var material = subMesh.getMaterial();
  75405. if (!material) {
  75406. return;
  75407. }
  75408. var scene = mesh.getScene();
  75409. var engine = scene.getEngine();
  75410. // Culling
  75411. engine.setState(material.backFaceCulling);
  75412. // Managing instances
  75413. var batch = mesh._getInstancesRenderList(subMesh._id);
  75414. if (batch.mustReturn) {
  75415. return;
  75416. }
  75417. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75418. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75419. var effect = _this._volumetricLightScatteringPass;
  75420. if (mesh === _this.mesh) {
  75421. if (subMesh.effect) {
  75422. effect = subMesh.effect;
  75423. }
  75424. else {
  75425. effect = material.getEffect();
  75426. }
  75427. }
  75428. engine.enableEffect(effect);
  75429. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75430. if (mesh === _this.mesh) {
  75431. material.bind(mesh.getWorldMatrix(), mesh);
  75432. }
  75433. else {
  75434. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75435. // Alpha test
  75436. if (material && material.needAlphaTesting()) {
  75437. var alphaTexture = material.getAlphaTestTexture();
  75438. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75439. if (alphaTexture) {
  75440. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75441. }
  75442. }
  75443. // Bones
  75444. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75445. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75446. }
  75447. }
  75448. // Draw
  75449. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75450. }
  75451. };
  75452. // Render target texture callbacks
  75453. var savedSceneClearColor;
  75454. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75455. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75456. savedSceneClearColor = scene.clearColor;
  75457. scene.clearColor = sceneClearColor;
  75458. });
  75459. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75460. scene.clearColor = savedSceneClearColor;
  75461. });
  75462. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75463. var engine = scene.getEngine();
  75464. var index;
  75465. if (depthOnlySubMeshes.length) {
  75466. engine.setColorWrite(false);
  75467. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75468. renderSubMesh(depthOnlySubMeshes.data[index]);
  75469. }
  75470. engine.setColorWrite(true);
  75471. }
  75472. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75473. renderSubMesh(opaqueSubMeshes.data[index]);
  75474. }
  75475. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75476. renderSubMesh(alphaTestSubMeshes.data[index]);
  75477. }
  75478. if (transparentSubMeshes.length) {
  75479. // Sort sub meshes
  75480. for (index = 0; index < transparentSubMeshes.length; index++) {
  75481. var submesh = transparentSubMeshes.data[index];
  75482. var boundingInfo = submesh.getBoundingInfo();
  75483. if (boundingInfo && scene.activeCamera) {
  75484. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75485. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75486. }
  75487. }
  75488. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75489. sortedArray.sort(function (a, b) {
  75490. // Alpha index first
  75491. if (a._alphaIndex > b._alphaIndex) {
  75492. return 1;
  75493. }
  75494. if (a._alphaIndex < b._alphaIndex) {
  75495. return -1;
  75496. }
  75497. // Then distance to camera
  75498. if (a._distanceToCamera < b._distanceToCamera) {
  75499. return 1;
  75500. }
  75501. if (a._distanceToCamera > b._distanceToCamera) {
  75502. return -1;
  75503. }
  75504. return 0;
  75505. });
  75506. // Render sub meshes
  75507. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75508. for (index = 0; index < sortedArray.length; index++) {
  75509. renderSubMesh(sortedArray[index]);
  75510. }
  75511. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75512. }
  75513. };
  75514. };
  75515. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75516. var transform = scene.getTransformMatrix();
  75517. var meshPosition;
  75518. if (this.useCustomMeshPosition) {
  75519. meshPosition = this.customMeshPosition;
  75520. }
  75521. else if (this.attachedNode) {
  75522. meshPosition = this.attachedNode.position;
  75523. }
  75524. else {
  75525. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75526. }
  75527. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75528. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75529. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75530. if (this.invert)
  75531. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75532. };
  75533. // Static methods
  75534. /**
  75535. * Creates a default mesh for the Volumeric Light Scattering post-process
  75536. * @param {string} The mesh name
  75537. * @param {BABYLON.Scene} The scene where to create the mesh
  75538. * @return {BABYLON.Mesh} the default mesh
  75539. */
  75540. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75541. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75542. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75543. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75544. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75545. mesh.material = material;
  75546. return mesh;
  75547. };
  75548. __decorate([
  75549. BABYLON.serializeAsVector3()
  75550. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75551. __decorate([
  75552. BABYLON.serialize()
  75553. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75554. __decorate([
  75555. BABYLON.serialize()
  75556. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75557. __decorate([
  75558. BABYLON.serializeAsMeshReference()
  75559. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75560. __decorate([
  75561. BABYLON.serialize()
  75562. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75563. __decorate([
  75564. BABYLON.serialize()
  75565. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75566. __decorate([
  75567. BABYLON.serialize()
  75568. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75569. __decorate([
  75570. BABYLON.serialize()
  75571. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75572. __decorate([
  75573. BABYLON.serialize()
  75574. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75575. return VolumetricLightScatteringPostProcess;
  75576. }(BABYLON.PostProcess));
  75577. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75578. })(BABYLON || (BABYLON = {}));
  75579. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75580. //
  75581. // This post-process allows the modification of rendered colors by using
  75582. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75583. //
  75584. // The object needs to be provided an url to a texture containing the color
  75585. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75586. // Use an image editing software to tweak the LUT to match your needs.
  75587. //
  75588. // For an example of a color LUT, see here:
  75589. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75590. // For explanations on color grading, see here:
  75591. // http://udn.epicgames.com/Three/ColorGrading.html
  75592. //
  75593. var BABYLON;
  75594. (function (BABYLON) {
  75595. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75596. __extends(ColorCorrectionPostProcess, _super);
  75597. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75598. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75599. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75600. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75601. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75602. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75603. _this.onApply = function (effect) {
  75604. effect.setTexture("colorTable", _this._colorTableTexture);
  75605. };
  75606. return _this;
  75607. }
  75608. return ColorCorrectionPostProcess;
  75609. }(BABYLON.PostProcess));
  75610. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75611. })(BABYLON || (BABYLON = {}));
  75612. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75613. var BABYLON;
  75614. (function (BABYLON) {
  75615. var TonemappingOperator;
  75616. (function (TonemappingOperator) {
  75617. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75618. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75619. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75620. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75621. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75622. ;
  75623. var TonemapPostProcess = /** @class */ (function (_super) {
  75624. __extends(TonemapPostProcess, _super);
  75625. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75627. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75628. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75629. _this._operator = _operator;
  75630. _this.exposureAdjustment = exposureAdjustment;
  75631. var defines = "#define ";
  75632. if (_this._operator === TonemappingOperator.Hable)
  75633. defines += "HABLE_TONEMAPPING";
  75634. else if (_this._operator === TonemappingOperator.Reinhard)
  75635. defines += "REINHARD_TONEMAPPING";
  75636. else if (_this._operator === TonemappingOperator.HejiDawson)
  75637. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75638. else if (_this._operator === TonemappingOperator.Photographic)
  75639. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75640. //sadly a second call to create the effect.
  75641. _this.updateEffect(defines);
  75642. _this.onApply = function (effect) {
  75643. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75644. };
  75645. return _this;
  75646. }
  75647. return TonemapPostProcess;
  75648. }(BABYLON.PostProcess));
  75649. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75650. })(BABYLON || (BABYLON = {}));
  75651. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75652. var BABYLON;
  75653. (function (BABYLON) {
  75654. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75655. __extends(DisplayPassPostProcess, _super);
  75656. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75657. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75658. }
  75659. return DisplayPassPostProcess;
  75660. }(BABYLON.PostProcess));
  75661. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75662. })(BABYLON || (BABYLON = {}));
  75663. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75664. var BABYLON;
  75665. (function (BABYLON) {
  75666. var HighlightsPostProcess = /** @class */ (function (_super) {
  75667. __extends(HighlightsPostProcess, _super);
  75668. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75670. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75671. }
  75672. return HighlightsPostProcess;
  75673. }(BABYLON.PostProcess));
  75674. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75675. })(BABYLON || (BABYLON = {}));
  75676. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75677. var BABYLON;
  75678. (function (BABYLON) {
  75679. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75680. __extends(ImageProcessingPostProcess, _super);
  75681. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75682. if (camera === void 0) { camera = null; }
  75683. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75684. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75685. _this._fromLinearSpace = true;
  75686. /**
  75687. * Defines cache preventing GC.
  75688. */
  75689. _this._defines = {
  75690. IMAGEPROCESSING: false,
  75691. VIGNETTE: false,
  75692. VIGNETTEBLENDMODEMULTIPLY: false,
  75693. VIGNETTEBLENDMODEOPAQUE: false,
  75694. TONEMAPPING: false,
  75695. CONTRAST: false,
  75696. COLORCURVES: false,
  75697. COLORGRADING: false,
  75698. COLORGRADING3D: false,
  75699. FROMLINEARSPACE: false,
  75700. SAMPLER3DGREENDEPTH: false,
  75701. SAMPLER3DBGRMAP: false,
  75702. IMAGEPROCESSINGPOSTPROCESS: false,
  75703. EXPOSURE: false,
  75704. };
  75705. // Setup the configuration as forced by the constructor. This would then not force the
  75706. // scene materials output in linear space and let untouched the default forward pass.
  75707. if (imageProcessingConfiguration) {
  75708. imageProcessingConfiguration.applyByPostProcess = true;
  75709. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75710. // This will cause the shader to be compiled
  75711. _this.fromLinearSpace = false;
  75712. }
  75713. // Setup the default processing configuration to the scene.
  75714. else {
  75715. _this._attachImageProcessingConfiguration(null, true);
  75716. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75717. }
  75718. _this.onApply = function (effect) {
  75719. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75720. };
  75721. return _this;
  75722. }
  75723. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75724. /**
  75725. * Gets the image processing configuration used either in this material.
  75726. */
  75727. get: function () {
  75728. return this._imageProcessingConfiguration;
  75729. },
  75730. /**
  75731. * Sets the Default image processing configuration used either in the this material.
  75732. *
  75733. * If sets to null, the scene one is in use.
  75734. */
  75735. set: function (value) {
  75736. this._attachImageProcessingConfiguration(value);
  75737. },
  75738. enumerable: true,
  75739. configurable: true
  75740. });
  75741. /**
  75742. * Attaches a new image processing configuration to the PBR Material.
  75743. * @param configuration
  75744. */
  75745. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75746. var _this = this;
  75747. if (doNotBuild === void 0) { doNotBuild = false; }
  75748. if (configuration === this._imageProcessingConfiguration) {
  75749. return;
  75750. }
  75751. // Detaches observer.
  75752. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75753. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75754. }
  75755. // Pick the scene configuration if needed.
  75756. if (!configuration) {
  75757. var scene = null;
  75758. var engine = this.getEngine();
  75759. var camera = this.getCamera();
  75760. if (camera) {
  75761. scene = camera.getScene();
  75762. }
  75763. else if (engine && engine.scenes) {
  75764. var scenes = engine.scenes;
  75765. scene = scenes[scenes.length - 1];
  75766. }
  75767. else {
  75768. scene = BABYLON.Engine.LastCreatedScene;
  75769. }
  75770. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75771. }
  75772. else {
  75773. this._imageProcessingConfiguration = configuration;
  75774. }
  75775. // Attaches observer.
  75776. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75777. _this._updateParameters();
  75778. });
  75779. // Ensure the effect will be rebuilt.
  75780. if (!doNotBuild) {
  75781. this._updateParameters();
  75782. }
  75783. };
  75784. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75785. /**
  75786. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75787. */
  75788. get: function () {
  75789. return this.imageProcessingConfiguration.colorCurves;
  75790. },
  75791. /**
  75792. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75793. */
  75794. set: function (value) {
  75795. this.imageProcessingConfiguration.colorCurves = value;
  75796. },
  75797. enumerable: true,
  75798. configurable: true
  75799. });
  75800. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75801. /**
  75802. * Gets wether the color curves effect is enabled.
  75803. */
  75804. get: function () {
  75805. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75806. },
  75807. /**
  75808. * Sets wether the color curves effect is enabled.
  75809. */
  75810. set: function (value) {
  75811. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75812. },
  75813. enumerable: true,
  75814. configurable: true
  75815. });
  75816. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75817. /**
  75818. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75819. */
  75820. get: function () {
  75821. return this.imageProcessingConfiguration.colorGradingTexture;
  75822. },
  75823. /**
  75824. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75825. */
  75826. set: function (value) {
  75827. this.imageProcessingConfiguration.colorGradingTexture = value;
  75828. },
  75829. enumerable: true,
  75830. configurable: true
  75831. });
  75832. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75833. /**
  75834. * Gets wether the color grading effect is enabled.
  75835. */
  75836. get: function () {
  75837. return this.imageProcessingConfiguration.colorGradingEnabled;
  75838. },
  75839. /**
  75840. * Gets wether the color grading effect is enabled.
  75841. */
  75842. set: function (value) {
  75843. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75849. /**
  75850. * Gets exposure used in the effect.
  75851. */
  75852. get: function () {
  75853. return this.imageProcessingConfiguration.exposure;
  75854. },
  75855. /**
  75856. * Sets exposure used in the effect.
  75857. */
  75858. set: function (value) {
  75859. this.imageProcessingConfiguration.exposure = value;
  75860. },
  75861. enumerable: true,
  75862. configurable: true
  75863. });
  75864. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75865. /**
  75866. * Gets wether tonemapping is enabled or not.
  75867. */
  75868. get: function () {
  75869. return this._imageProcessingConfiguration.toneMappingEnabled;
  75870. },
  75871. /**
  75872. * Sets wether tonemapping is enabled or not
  75873. */
  75874. set: function (value) {
  75875. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75876. },
  75877. enumerable: true,
  75878. configurable: true
  75879. });
  75880. ;
  75881. ;
  75882. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75883. /**
  75884. * Gets contrast used in the effect.
  75885. */
  75886. get: function () {
  75887. return this.imageProcessingConfiguration.contrast;
  75888. },
  75889. /**
  75890. * Sets contrast used in the effect.
  75891. */
  75892. set: function (value) {
  75893. this.imageProcessingConfiguration.contrast = value;
  75894. },
  75895. enumerable: true,
  75896. configurable: true
  75897. });
  75898. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75899. /**
  75900. * Gets Vignette stretch size.
  75901. */
  75902. get: function () {
  75903. return this.imageProcessingConfiguration.vignetteStretch;
  75904. },
  75905. /**
  75906. * Sets Vignette stretch size.
  75907. */
  75908. set: function (value) {
  75909. this.imageProcessingConfiguration.vignetteStretch = value;
  75910. },
  75911. enumerable: true,
  75912. configurable: true
  75913. });
  75914. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75915. /**
  75916. * Gets Vignette centre X Offset.
  75917. */
  75918. get: function () {
  75919. return this.imageProcessingConfiguration.vignetteCentreX;
  75920. },
  75921. /**
  75922. * Sets Vignette centre X Offset.
  75923. */
  75924. set: function (value) {
  75925. this.imageProcessingConfiguration.vignetteCentreX = value;
  75926. },
  75927. enumerable: true,
  75928. configurable: true
  75929. });
  75930. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75931. /**
  75932. * Gets Vignette centre Y Offset.
  75933. */
  75934. get: function () {
  75935. return this.imageProcessingConfiguration.vignetteCentreY;
  75936. },
  75937. /**
  75938. * Sets Vignette centre Y Offset.
  75939. */
  75940. set: function (value) {
  75941. this.imageProcessingConfiguration.vignetteCentreY = value;
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75947. /**
  75948. * Gets Vignette weight or intensity of the vignette effect.
  75949. */
  75950. get: function () {
  75951. return this.imageProcessingConfiguration.vignetteWeight;
  75952. },
  75953. /**
  75954. * Sets Vignette weight or intensity of the vignette effect.
  75955. */
  75956. set: function (value) {
  75957. this.imageProcessingConfiguration.vignetteWeight = value;
  75958. },
  75959. enumerable: true,
  75960. configurable: true
  75961. });
  75962. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75963. /**
  75964. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75965. * if vignetteEnabled is set to true.
  75966. */
  75967. get: function () {
  75968. return this.imageProcessingConfiguration.vignetteColor;
  75969. },
  75970. /**
  75971. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75972. * if vignetteEnabled is set to true.
  75973. */
  75974. set: function (value) {
  75975. this.imageProcessingConfiguration.vignetteColor = value;
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75981. /**
  75982. * Gets Camera field of view used by the Vignette effect.
  75983. */
  75984. get: function () {
  75985. return this.imageProcessingConfiguration.vignetteCameraFov;
  75986. },
  75987. /**
  75988. * Sets Camera field of view used by the Vignette effect.
  75989. */
  75990. set: function (value) {
  75991. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75992. },
  75993. enumerable: true,
  75994. configurable: true
  75995. });
  75996. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75997. /**
  75998. * Gets the vignette blend mode allowing different kind of effect.
  75999. */
  76000. get: function () {
  76001. return this.imageProcessingConfiguration.vignetteBlendMode;
  76002. },
  76003. /**
  76004. * Sets the vignette blend mode allowing different kind of effect.
  76005. */
  76006. set: function (value) {
  76007. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76008. },
  76009. enumerable: true,
  76010. configurable: true
  76011. });
  76012. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76013. /**
  76014. * Gets wether the vignette effect is enabled.
  76015. */
  76016. get: function () {
  76017. return this.imageProcessingConfiguration.vignetteEnabled;
  76018. },
  76019. /**
  76020. * Sets wether the vignette effect is enabled.
  76021. */
  76022. set: function (value) {
  76023. this.imageProcessingConfiguration.vignetteEnabled = value;
  76024. },
  76025. enumerable: true,
  76026. configurable: true
  76027. });
  76028. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76029. /**
  76030. * Gets wether the input of the processing is in Gamma or Linear Space.
  76031. */
  76032. get: function () {
  76033. return this._fromLinearSpace;
  76034. },
  76035. /**
  76036. * Sets wether the input of the processing is in Gamma or Linear Space.
  76037. */
  76038. set: function (value) {
  76039. if (this._fromLinearSpace === value) {
  76040. return;
  76041. }
  76042. this._fromLinearSpace = value;
  76043. this._updateParameters();
  76044. },
  76045. enumerable: true,
  76046. configurable: true
  76047. });
  76048. ImageProcessingPostProcess.prototype.getClassName = function () {
  76049. return "ImageProcessingPostProcess";
  76050. };
  76051. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76052. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76053. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76054. var defines = "";
  76055. for (var define in this._defines) {
  76056. if (this._defines[define]) {
  76057. defines += "#define " + define + ";\r\n";
  76058. }
  76059. }
  76060. var samplers = ["textureSampler"];
  76061. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76062. var uniforms = ["scale"];
  76063. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76064. this.updateEffect(defines, uniforms, samplers);
  76065. };
  76066. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76067. _super.prototype.dispose.call(this, camera);
  76068. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76069. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76070. }
  76071. this.imageProcessingConfiguration.applyByPostProcess = false;
  76072. };
  76073. __decorate([
  76074. BABYLON.serialize()
  76075. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76076. return ImageProcessingPostProcess;
  76077. }(BABYLON.PostProcess));
  76078. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76079. })(BABYLON || (BABYLON = {}));
  76080. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76081. var BABYLON;
  76082. (function (BABYLON) {
  76083. var Bone = /** @class */ (function (_super) {
  76084. __extends(Bone, _super);
  76085. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76086. if (parentBone === void 0) { parentBone = null; }
  76087. if (localMatrix === void 0) { localMatrix = null; }
  76088. if (restPose === void 0) { restPose = null; }
  76089. if (baseMatrix === void 0) { baseMatrix = null; }
  76090. if (index === void 0) { index = null; }
  76091. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76092. _this.name = name;
  76093. _this.children = new Array();
  76094. _this.animations = new Array();
  76095. // Set this value to map this bone to a different index in the transform matrices.
  76096. // Set this value to -1 to exclude the bone from the transform matrices.
  76097. _this._index = null;
  76098. _this._worldTransform = new BABYLON.Matrix();
  76099. _this._absoluteTransform = new BABYLON.Matrix();
  76100. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76101. _this._scaleMatrix = BABYLON.Matrix.Identity();
  76102. _this._scaleVector = BABYLON.Vector3.One();
  76103. _this._negateScaleChildren = BABYLON.Vector3.One();
  76104. _this._scalingDeterminant = 1;
  76105. _this._skeleton = skeleton;
  76106. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76107. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76108. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76109. _this._index = index;
  76110. skeleton.bones.push(_this);
  76111. _this.setParent(parentBone, false);
  76112. _this._updateDifferenceMatrix();
  76113. return _this;
  76114. }
  76115. Object.defineProperty(Bone.prototype, "_matrix", {
  76116. get: function () {
  76117. return this._localMatrix;
  76118. },
  76119. set: function (value) {
  76120. this._localMatrix.copyFrom(value);
  76121. },
  76122. enumerable: true,
  76123. configurable: true
  76124. });
  76125. // Members
  76126. Bone.prototype.getSkeleton = function () {
  76127. return this._skeleton;
  76128. };
  76129. Bone.prototype.getParent = function () {
  76130. return this._parent;
  76131. };
  76132. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76133. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76134. if (this._parent === parent) {
  76135. return;
  76136. }
  76137. if (this._parent) {
  76138. var index = this._parent.children.indexOf(this);
  76139. if (index !== -1) {
  76140. this._parent.children.splice(index, 1);
  76141. }
  76142. }
  76143. this._parent = parent;
  76144. if (this._parent) {
  76145. this._parent.children.push(this);
  76146. }
  76147. if (updateDifferenceMatrix) {
  76148. this._updateDifferenceMatrix();
  76149. }
  76150. this.markAsDirty();
  76151. };
  76152. Bone.prototype.getLocalMatrix = function () {
  76153. return this._localMatrix;
  76154. };
  76155. Bone.prototype.getBaseMatrix = function () {
  76156. return this._baseMatrix;
  76157. };
  76158. Bone.prototype.getRestPose = function () {
  76159. return this._restPose;
  76160. };
  76161. Bone.prototype.returnToRest = function () {
  76162. this.updateMatrix(this._restPose.clone());
  76163. };
  76164. Bone.prototype.getWorldMatrix = function () {
  76165. return this._worldTransform;
  76166. };
  76167. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76168. return this._invertedAbsoluteTransform;
  76169. };
  76170. Bone.prototype.getAbsoluteTransform = function () {
  76171. return this._absoluteTransform;
  76172. };
  76173. Object.defineProperty(Bone.prototype, "position", {
  76174. // Properties (matches AbstractMesh properties)
  76175. get: function () {
  76176. return this.getPosition();
  76177. },
  76178. set: function (newPosition) {
  76179. this.setPosition(newPosition);
  76180. },
  76181. enumerable: true,
  76182. configurable: true
  76183. });
  76184. Object.defineProperty(Bone.prototype, "rotation", {
  76185. get: function () {
  76186. return this.getRotation();
  76187. },
  76188. set: function (newRotation) {
  76189. this.setRotation(newRotation);
  76190. },
  76191. enumerable: true,
  76192. configurable: true
  76193. });
  76194. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76195. get: function () {
  76196. return this.getRotationQuaternion();
  76197. },
  76198. set: function (newRotation) {
  76199. this.setRotationQuaternion(newRotation);
  76200. },
  76201. enumerable: true,
  76202. configurable: true
  76203. });
  76204. Object.defineProperty(Bone.prototype, "scaling", {
  76205. get: function () {
  76206. var value = BABYLON.Vector3.One();
  76207. this._localMatrix.decompose(value, undefined, undefined);
  76208. return value;
  76209. },
  76210. set: function (newScaling) {
  76211. this._localMatrix.decompose(undefined, Bone._tmpQuat, Bone._tmpVecs[0]);
  76212. BABYLON.Matrix.ComposeToRef(newScaling, Bone._tmpQuat, Bone._tmpVecs[0], this._localMatrix);
  76213. this.markAsDirty();
  76214. },
  76215. enumerable: true,
  76216. configurable: true
  76217. });
  76218. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76219. /**
  76220. * Gets the animation properties override
  76221. */
  76222. get: function () {
  76223. return this._skeleton.animationPropertiesOverride;
  76224. },
  76225. enumerable: true,
  76226. configurable: true
  76227. });
  76228. // Methods
  76229. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  76230. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76231. this._baseMatrix.copyFrom(matrix);
  76232. this._localMatrix.copyFrom(matrix);
  76233. if (updateDifferenceMatrix) {
  76234. this._updateDifferenceMatrix();
  76235. }
  76236. this.markAsDirty();
  76237. };
  76238. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  76239. if (!rootMatrix) {
  76240. rootMatrix = this._baseMatrix;
  76241. }
  76242. if (this._parent) {
  76243. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76244. }
  76245. else {
  76246. this._absoluteTransform.copyFrom(rootMatrix);
  76247. }
  76248. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76249. for (var index = 0; index < this.children.length; index++) {
  76250. this.children[index]._updateDifferenceMatrix();
  76251. }
  76252. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76253. };
  76254. Bone.prototype.markAsDirty = function () {
  76255. this._currentRenderId++;
  76256. this._childRenderId++;
  76257. this._skeleton._markAsDirty();
  76258. };
  76259. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76260. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76261. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76262. // all animation may be coming from a library skeleton, so may need to create animation
  76263. if (this.animations.length === 0) {
  76264. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76265. this.animations[0].setKeys([]);
  76266. }
  76267. // get animation info / verify there is such a range from the source bone
  76268. var sourceRange = source.animations[0].getRange(rangeName);
  76269. if (!sourceRange) {
  76270. return false;
  76271. }
  76272. var from = sourceRange.from;
  76273. var to = sourceRange.to;
  76274. var sourceKeys = source.animations[0].getKeys();
  76275. // rescaling prep
  76276. var sourceBoneLength = source.length;
  76277. var sourceParent = source.getParent();
  76278. var parent = this.getParent();
  76279. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76280. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76281. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76282. var destKeys = this.animations[0].getKeys();
  76283. // loop vars declaration
  76284. var orig;
  76285. var origTranslation;
  76286. var mat;
  76287. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76288. orig = sourceKeys[key];
  76289. if (orig.frame >= from && orig.frame <= to) {
  76290. if (rescaleAsRequired) {
  76291. mat = orig.value.clone();
  76292. // scale based on parent ratio, when bone has parent
  76293. if (parentScalingReqd) {
  76294. origTranslation = mat.getTranslation();
  76295. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76296. // scale based on skeleton dimension ratio when root bone, and value is passed
  76297. }
  76298. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76299. origTranslation = mat.getTranslation();
  76300. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76301. // use original when root bone, and no data for skelDimensionsRatio
  76302. }
  76303. else {
  76304. mat = orig.value;
  76305. }
  76306. }
  76307. else {
  76308. mat = orig.value;
  76309. }
  76310. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76311. }
  76312. }
  76313. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76314. return true;
  76315. };
  76316. /**
  76317. * Translate the bone in local or world space
  76318. * @param vec The amount to translate the bone
  76319. * @param space The space that the translation is in
  76320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76321. */
  76322. Bone.prototype.translate = function (vec, space, mesh) {
  76323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76324. var lm = this.getLocalMatrix();
  76325. if (space == BABYLON.Space.LOCAL) {
  76326. lm.m[12] += vec.x;
  76327. lm.m[13] += vec.y;
  76328. lm.m[14] += vec.z;
  76329. }
  76330. else {
  76331. var wm = null;
  76332. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76333. if (mesh) {
  76334. wm = mesh.getWorldMatrix();
  76335. }
  76336. this._skeleton.computeAbsoluteTransforms();
  76337. var tmat = Bone._tmpMats[0];
  76338. var tvec = Bone._tmpVecs[0];
  76339. if (this._parent) {
  76340. if (mesh && wm) {
  76341. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76342. tmat.multiplyToRef(wm, tmat);
  76343. }
  76344. else {
  76345. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76346. }
  76347. }
  76348. tmat.m[12] = 0;
  76349. tmat.m[13] = 0;
  76350. tmat.m[14] = 0;
  76351. tmat.invert();
  76352. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76353. lm.m[12] += tvec.x;
  76354. lm.m[13] += tvec.y;
  76355. lm.m[14] += tvec.z;
  76356. }
  76357. this.markAsDirty();
  76358. };
  76359. /**
  76360. * Set the postion of the bone in local or world space
  76361. * @param position The position to set the bone
  76362. * @param space The space that the position is in
  76363. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76364. */
  76365. Bone.prototype.setPosition = function (position, space, mesh) {
  76366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76367. var lm = this.getLocalMatrix();
  76368. if (space == BABYLON.Space.LOCAL) {
  76369. lm.m[12] = position.x;
  76370. lm.m[13] = position.y;
  76371. lm.m[14] = position.z;
  76372. }
  76373. else {
  76374. var wm = null;
  76375. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76376. if (mesh) {
  76377. wm = mesh.getWorldMatrix();
  76378. }
  76379. this._skeleton.computeAbsoluteTransforms();
  76380. var tmat = Bone._tmpMats[0];
  76381. var vec = Bone._tmpVecs[0];
  76382. if (this._parent) {
  76383. if (mesh && wm) {
  76384. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76385. tmat.multiplyToRef(wm, tmat);
  76386. }
  76387. else {
  76388. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76389. }
  76390. }
  76391. tmat.invert();
  76392. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76393. lm.m[12] = vec.x;
  76394. lm.m[13] = vec.y;
  76395. lm.m[14] = vec.z;
  76396. }
  76397. this.markAsDirty();
  76398. };
  76399. /**
  76400. * Set the absolute postion of the bone (world space)
  76401. * @param position The position to set the bone
  76402. * @param mesh The mesh that this bone is attached to
  76403. */
  76404. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76405. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76406. };
  76407. /**
  76408. * Adds an additional scale to the bone on the x, y and z axes
  76409. * @param x The additional scale of the bone on the x axis
  76410. * @param y The additional scale of the bone on the y axis
  76411. * @param z The additional scale of the bone on the z axis
  76412. * @param scaleChildren Set this to true if children of the bone should be scaled
  76413. */
  76414. Bone.prototype.setAdditionalScale = function (x, y, z, scaleChildren) {
  76415. if (scaleChildren === void 0) { scaleChildren = false; }
  76416. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  76417. if (!scaleChildren) {
  76418. this._negateScaleChildren.x = 1 / x;
  76419. this._negateScaleChildren.y = 1 / y;
  76420. this._negateScaleChildren.z = 1 / z;
  76421. }
  76422. this._syncScaleVector();
  76423. }
  76424. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  76425. };
  76426. /**
  76427. * Scale the bone on the x, y and z axes.
  76428. * @param x The amount to scale the bone on the x axis.
  76429. * @param x The amount to scale the bone on the y axis.
  76430. * @param z The amount to scale the bone on the z axis.
  76431. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76432. */
  76433. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  76434. if (scaleChildren === void 0) { scaleChildren = false; }
  76435. var locMat = this.getLocalMatrix();
  76436. var origLocMat = Bone._tmpMats[0];
  76437. origLocMat.copyFrom(locMat);
  76438. var origLocMatInv = Bone._tmpMats[1];
  76439. origLocMatInv.copyFrom(origLocMat);
  76440. origLocMatInv.invert();
  76441. var scaleMat = Bone._tmpMats[2];
  76442. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  76443. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  76444. this._scaleVector.x *= x;
  76445. this._scaleVector.y *= y;
  76446. this._scaleVector.z *= z;
  76447. locMat.multiplyToRef(origLocMatInv, locMat);
  76448. locMat.multiplyToRef(scaleMat, locMat);
  76449. locMat.multiplyToRef(origLocMat, locMat);
  76450. var parent = this.getParent();
  76451. if (parent) {
  76452. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  76453. }
  76454. else {
  76455. this.getAbsoluteTransform().copyFrom(locMat);
  76456. }
  76457. var len = this.children.length;
  76458. scaleMat.invert();
  76459. for (var i = 0; i < len; i++) {
  76460. var child = this.children[i];
  76461. var cm = child.getLocalMatrix();
  76462. cm.multiplyToRef(scaleMat, cm);
  76463. var lm = child.getLocalMatrix();
  76464. lm.m[12] *= x;
  76465. lm.m[13] *= y;
  76466. lm.m[14] *= z;
  76467. }
  76468. this.computeAbsoluteTransforms();
  76469. if (scaleChildren) {
  76470. for (var i = 0; i < len; i++) {
  76471. this.children[i].scale(x, y, z, scaleChildren);
  76472. }
  76473. }
  76474. this.markAsDirty();
  76475. };
  76476. /**
  76477. * Set the yaw, pitch, and roll of the bone in local or world space.
  76478. * @param yaw The rotation of the bone on the y axis.
  76479. * @param pitch The rotation of the bone on the x axis.
  76480. * @param roll The rotation of the bone on the z axis.
  76481. * @param space The space that the axes of rotation are in.
  76482. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76483. */
  76484. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76485. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76486. var rotMatInv = Bone._tmpMats[0];
  76487. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76488. return;
  76489. }
  76490. var rotMat = Bone._tmpMats[1];
  76491. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76492. rotMatInv.multiplyToRef(rotMat, rotMat);
  76493. this._rotateWithMatrix(rotMat, space, mesh);
  76494. };
  76495. /**
  76496. * Rotate the bone on an axis in local or world space.
  76497. * @param axis The axis to rotate the bone on.
  76498. * @param amount The amount to rotate the bone.
  76499. * @param space The space that the axis is in.
  76500. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76501. */
  76502. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76503. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76504. var rmat = Bone._tmpMats[0];
  76505. rmat.m[12] = 0;
  76506. rmat.m[13] = 0;
  76507. rmat.m[14] = 0;
  76508. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76509. this._rotateWithMatrix(rmat, space, mesh);
  76510. };
  76511. /**
  76512. * Set the rotation of the bone to a particular axis angle in local or world space.
  76513. * @param axis The axis to rotate the bone on.
  76514. * @param angle The angle that the bone should be rotated to.
  76515. * @param space The space that the axis is in.
  76516. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76517. */
  76518. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76520. var rotMatInv = Bone._tmpMats[0];
  76521. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76522. return;
  76523. }
  76524. var rotMat = Bone._tmpMats[1];
  76525. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76526. rotMatInv.multiplyToRef(rotMat, rotMat);
  76527. this._rotateWithMatrix(rotMat, space, mesh);
  76528. };
  76529. /**
  76530. * Set the euler rotation of the bone in local of world space.
  76531. * @param rotation The euler rotation that the bone should be set to.
  76532. * @param space The space that the rotation is in.
  76533. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76534. */
  76535. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76536. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76537. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76538. };
  76539. /**
  76540. * Set the quaternion rotation of the bone in local of world space.
  76541. * @param quat The quaternion rotation that the bone should be set to.
  76542. * @param space The space that the rotation is in.
  76543. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76544. */
  76545. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76546. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76547. if (space === BABYLON.Space.LOCAL) {
  76548. var position = Bone._tmpVecs[0];
  76549. var scaling = Bone._tmpVecs[1];
  76550. var localMatrix = this.getLocalMatrix();
  76551. localMatrix.decompose(scaling, undefined, position);
  76552. BABYLON.Matrix.ComposeToRef(scaling, quat, position, localMatrix);
  76553. this.markAsDirty();
  76554. return;
  76555. }
  76556. var rotMatInv = Bone._tmpMats[0];
  76557. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76558. return;
  76559. }
  76560. var rotMat = Bone._tmpMats[1];
  76561. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76562. rotMatInv.multiplyToRef(rotMat, rotMat);
  76563. this._rotateWithMatrix(rotMat, space, mesh);
  76564. };
  76565. /**
  76566. * Set the rotation matrix of the bone in local of world space.
  76567. * @param rotMat The rotation matrix that the bone should be set to.
  76568. * @param space The space that the rotation is in.
  76569. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76570. */
  76571. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76572. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76573. var rotMatInv = Bone._tmpMats[0];
  76574. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76575. return;
  76576. }
  76577. var rotMat2 = Bone._tmpMats[1];
  76578. rotMat2.copyFrom(rotMat);
  76579. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76580. this._rotateWithMatrix(rotMat2, space, mesh);
  76581. };
  76582. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76584. var lmat = this.getLocalMatrix();
  76585. var lx = lmat.m[12];
  76586. var ly = lmat.m[13];
  76587. var lz = lmat.m[14];
  76588. var parent = this.getParent();
  76589. var parentScale = Bone._tmpMats[3];
  76590. var parentScaleInv = Bone._tmpMats[4];
  76591. if (parent) {
  76592. if (space == BABYLON.Space.WORLD) {
  76593. if (mesh) {
  76594. parentScale.copyFrom(mesh.getWorldMatrix());
  76595. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76596. }
  76597. else {
  76598. parentScale.copyFrom(parent.getAbsoluteTransform());
  76599. }
  76600. }
  76601. else {
  76602. parentScale = parent._scaleMatrix;
  76603. }
  76604. parentScaleInv.copyFrom(parentScale);
  76605. parentScaleInv.invert();
  76606. lmat.multiplyToRef(parentScale, lmat);
  76607. lmat.multiplyToRef(rmat, lmat);
  76608. lmat.multiplyToRef(parentScaleInv, lmat);
  76609. }
  76610. else {
  76611. if (space == BABYLON.Space.WORLD && mesh) {
  76612. parentScale.copyFrom(mesh.getWorldMatrix());
  76613. parentScaleInv.copyFrom(parentScale);
  76614. parentScaleInv.invert();
  76615. lmat.multiplyToRef(parentScale, lmat);
  76616. lmat.multiplyToRef(rmat, lmat);
  76617. lmat.multiplyToRef(parentScaleInv, lmat);
  76618. }
  76619. else {
  76620. lmat.multiplyToRef(rmat, lmat);
  76621. }
  76622. }
  76623. lmat.m[12] = lx;
  76624. lmat.m[13] = ly;
  76625. lmat.m[14] = lz;
  76626. this.computeAbsoluteTransforms();
  76627. this.markAsDirty();
  76628. };
  76629. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76631. if (space == BABYLON.Space.WORLD) {
  76632. var scaleMatrix = Bone._tmpMats[2];
  76633. scaleMatrix.copyFrom(this._scaleMatrix);
  76634. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76635. if (mesh) {
  76636. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76637. var meshScale = Bone._tmpMats[3];
  76638. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76639. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76640. }
  76641. rotMatInv.invert();
  76642. if (isNaN(rotMatInv.m[0])) {
  76643. // Matrix failed to invert.
  76644. // This can happen if scale is zero for example.
  76645. return false;
  76646. }
  76647. scaleMatrix.m[0] *= this._scalingDeterminant;
  76648. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76649. }
  76650. else {
  76651. rotMatInv.copyFrom(this.getLocalMatrix());
  76652. rotMatInv.invert();
  76653. if (isNaN(rotMatInv.m[0])) {
  76654. // Matrix failed to invert.
  76655. // This can happen if scale is zero for example.
  76656. return false;
  76657. }
  76658. var scaleMatrix = Bone._tmpMats[2];
  76659. scaleMatrix.copyFrom(this._scaleMatrix);
  76660. if (this._parent) {
  76661. var pscaleMatrix = Bone._tmpMats[3];
  76662. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76663. pscaleMatrix.invert();
  76664. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76665. }
  76666. else {
  76667. scaleMatrix.m[0] *= this._scalingDeterminant;
  76668. }
  76669. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76670. }
  76671. return true;
  76672. };
  76673. /**
  76674. * Get the additional scale of the bone
  76675. * @returns the additional scale of the bone
  76676. */
  76677. Bone.prototype.getAdditionalScale = function () {
  76678. return this._scaleVector.clone();
  76679. };
  76680. /**
  76681. * Copy the additional scale of the bone to a vector3.
  76682. * @param result The vector3 to copy the additional scale to
  76683. */
  76684. Bone.prototype.getAdditionalScaleToRef = function (result) {
  76685. result.copyFrom(this._scaleVector);
  76686. };
  76687. /**
  76688. * Get the position of the bone in local or world space.
  76689. * @param space The space that the returned position is in.
  76690. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76691. * @returns The position of the bone
  76692. */
  76693. Bone.prototype.getPosition = function (space, mesh) {
  76694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76695. if (mesh === void 0) { mesh = null; }
  76696. var pos = BABYLON.Vector3.Zero();
  76697. this.getPositionToRef(space, mesh, pos);
  76698. return pos;
  76699. };
  76700. /**
  76701. * Copy the position of the bone to a vector3 in local or world space.
  76702. * @param space The space that the returned position is in.
  76703. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76704. * @param result The vector3 to copy the position to.
  76705. */
  76706. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76708. if (space == BABYLON.Space.LOCAL) {
  76709. var lm = this.getLocalMatrix();
  76710. result.x = lm.m[12];
  76711. result.y = lm.m[13];
  76712. result.z = lm.m[14];
  76713. }
  76714. else {
  76715. var wm = null;
  76716. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76717. if (mesh) {
  76718. wm = mesh.getWorldMatrix();
  76719. }
  76720. this._skeleton.computeAbsoluteTransforms();
  76721. var tmat = Bone._tmpMats[0];
  76722. if (mesh && wm) {
  76723. tmat.copyFrom(this.getAbsoluteTransform());
  76724. tmat.multiplyToRef(wm, tmat);
  76725. }
  76726. else {
  76727. tmat = this.getAbsoluteTransform();
  76728. }
  76729. result.x = tmat.m[12];
  76730. result.y = tmat.m[13];
  76731. result.z = tmat.m[14];
  76732. }
  76733. };
  76734. /**
  76735. * Get the absolute position of the bone (world space).
  76736. * @param mesh The mesh that this bone is attached to.
  76737. * @returns The absolute position of the bone
  76738. */
  76739. Bone.prototype.getAbsolutePosition = function (mesh) {
  76740. if (mesh === void 0) { mesh = null; }
  76741. var pos = BABYLON.Vector3.Zero();
  76742. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76743. return pos;
  76744. };
  76745. /**
  76746. * Copy the absolute position of the bone (world space) to the result param.
  76747. * @param mesh The mesh that this bone is attached to.
  76748. * @param result The vector3 to copy the absolute position to.
  76749. */
  76750. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76751. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76752. };
  76753. /**
  76754. * Compute the absolute transforms of this bone and its children.
  76755. */
  76756. Bone.prototype.computeAbsoluteTransforms = function () {
  76757. if (this._parent) {
  76758. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76759. }
  76760. else {
  76761. this._absoluteTransform.copyFrom(this._localMatrix);
  76762. var poseMatrix = this._skeleton.getPoseMatrix();
  76763. if (poseMatrix) {
  76764. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76765. }
  76766. }
  76767. var children = this.children;
  76768. var len = children.length;
  76769. for (var i = 0; i < len; i++) {
  76770. children[i].computeAbsoluteTransforms();
  76771. }
  76772. };
  76773. Bone.prototype._syncScaleVector = function () {
  76774. var lm = this.getLocalMatrix();
  76775. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76776. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76777. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76778. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76779. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76780. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76781. this._scaleVector.x = xs * Math.sqrt(xsq);
  76782. this._scaleVector.y = ys * Math.sqrt(ysq);
  76783. this._scaleVector.z = zs * Math.sqrt(zsq);
  76784. if (this._parent) {
  76785. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76786. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76787. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76788. }
  76789. 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);
  76790. };
  76791. /**
  76792. * Get the world direction from an axis that is in the local space of the bone.
  76793. * @param localAxis The local direction that is used to compute the world direction.
  76794. * @param mesh The mesh that this bone is attached to.
  76795. * @returns The world direction
  76796. */
  76797. Bone.prototype.getDirection = function (localAxis, mesh) {
  76798. if (mesh === void 0) { mesh = null; }
  76799. var result = BABYLON.Vector3.Zero();
  76800. this.getDirectionToRef(localAxis, mesh, result);
  76801. return result;
  76802. };
  76803. /**
  76804. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76805. * @param localAxis The local direction that is used to compute the world direction.
  76806. * @param mesh The mesh that this bone is attached to.
  76807. * @param result The vector3 that the world direction will be copied to.
  76808. */
  76809. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76810. if (mesh === void 0) { mesh = null; }
  76811. var wm = null;
  76812. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76813. if (mesh) {
  76814. wm = mesh.getWorldMatrix();
  76815. }
  76816. this._skeleton.computeAbsoluteTransforms();
  76817. var mat = Bone._tmpMats[0];
  76818. mat.copyFrom(this.getAbsoluteTransform());
  76819. if (mesh && wm) {
  76820. mat.multiplyToRef(wm, mat);
  76821. }
  76822. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76823. result.normalize();
  76824. };
  76825. /**
  76826. * Get the euler rotation of the bone in local or world space.
  76827. * @param space The space that the rotation should be in.
  76828. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76829. * @returns The euler rotation
  76830. */
  76831. Bone.prototype.getRotation = function (space, mesh) {
  76832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76833. if (mesh === void 0) { mesh = null; }
  76834. var result = BABYLON.Vector3.Zero();
  76835. this.getRotationToRef(space, mesh, result);
  76836. return result;
  76837. };
  76838. /**
  76839. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76840. * @param space The space that the rotation should be in.
  76841. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76842. * @param result The vector3 that the rotation should be copied to.
  76843. */
  76844. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76846. if (mesh === void 0) { mesh = null; }
  76847. var quat = Bone._tmpQuat;
  76848. this.getRotationQuaternionToRef(space, mesh, quat);
  76849. quat.toEulerAnglesToRef(result);
  76850. };
  76851. /**
  76852. * Get the quaternion rotation of the bone in either local or world space.
  76853. * @param space The space that the rotation should be in.
  76854. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76855. * @returns The quaternion rotation
  76856. */
  76857. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76859. if (mesh === void 0) { mesh = null; }
  76860. var result = BABYLON.Quaternion.Identity();
  76861. this.getRotationQuaternionToRef(space, mesh, result);
  76862. return result;
  76863. };
  76864. /**
  76865. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76866. * @param space The space that the rotation should be in.
  76867. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76868. * @param result The quaternion that the rotation should be copied to.
  76869. */
  76870. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76871. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76872. if (mesh === void 0) { mesh = null; }
  76873. if (space == BABYLON.Space.LOCAL) {
  76874. this.getLocalMatrix().decompose(undefined, result, undefined);
  76875. }
  76876. else {
  76877. var mat = Bone._tmpMats[0];
  76878. var amat = this.getAbsoluteTransform();
  76879. if (mesh) {
  76880. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76881. }
  76882. else {
  76883. mat.copyFrom(amat);
  76884. }
  76885. mat.m[0] *= this._scalingDeterminant;
  76886. mat.m[1] *= this._scalingDeterminant;
  76887. mat.m[2] *= this._scalingDeterminant;
  76888. mat.decompose(undefined, result, undefined);
  76889. }
  76890. };
  76891. /**
  76892. * Get the rotation matrix of the bone in local or world space.
  76893. * @param space The space that the rotation should be in.
  76894. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76895. * @returns The rotation matrix
  76896. */
  76897. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76899. var result = BABYLON.Matrix.Identity();
  76900. this.getRotationMatrixToRef(space, mesh, result);
  76901. return result;
  76902. };
  76903. /**
  76904. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  76905. * @param space The space that the rotation should be in
  76906. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76907. * @param result The quaternion that the rotation should be copied to
  76908. */
  76909. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76911. if (space == BABYLON.Space.LOCAL) {
  76912. this.getLocalMatrix().getRotationMatrixToRef(result);
  76913. }
  76914. else {
  76915. var mat = Bone._tmpMats[0];
  76916. var amat = this.getAbsoluteTransform();
  76917. if (mesh) {
  76918. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76919. }
  76920. else {
  76921. mat.copyFrom(amat);
  76922. }
  76923. mat.m[0] *= this._scalingDeterminant;
  76924. mat.m[1] *= this._scalingDeterminant;
  76925. mat.m[2] *= this._scalingDeterminant;
  76926. mat.getRotationMatrixToRef(result);
  76927. }
  76928. };
  76929. /**
  76930. * Get the world position of a point that is in the local space of the bone
  76931. * @param position The local position
  76932. * @param mesh The mesh that this bone is attached to
  76933. * @returns The world position
  76934. */
  76935. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76936. if (mesh === void 0) { mesh = null; }
  76937. var result = BABYLON.Vector3.Zero();
  76938. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76939. return result;
  76940. };
  76941. /**
  76942. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  76943. * @param position The local position
  76944. * @param mesh The mesh that this bone is attached to
  76945. * @param result The vector3 that the world position should be copied to
  76946. */
  76947. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76948. if (mesh === void 0) { mesh = null; }
  76949. var wm = null;
  76950. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76951. if (mesh) {
  76952. wm = mesh.getWorldMatrix();
  76953. }
  76954. this._skeleton.computeAbsoluteTransforms();
  76955. var tmat = Bone._tmpMats[0];
  76956. if (mesh && wm) {
  76957. tmat.copyFrom(this.getAbsoluteTransform());
  76958. tmat.multiplyToRef(wm, tmat);
  76959. }
  76960. else {
  76961. tmat = this.getAbsoluteTransform();
  76962. }
  76963. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76964. };
  76965. /**
  76966. * Get the local position of a point that is in world space
  76967. * @param position The world position
  76968. * @param mesh The mesh that this bone is attached to
  76969. * @returns The local position
  76970. */
  76971. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76972. if (mesh === void 0) { mesh = null; }
  76973. var result = BABYLON.Vector3.Zero();
  76974. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76975. return result;
  76976. };
  76977. /**
  76978. * Get the local position of a point that is in world space and copy it to the result param
  76979. * @param position The world position
  76980. * @param mesh The mesh that this bone is attached to
  76981. * @param result The vector3 that the local position should be copied to
  76982. */
  76983. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76984. if (mesh === void 0) { mesh = null; }
  76985. var wm = null;
  76986. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76987. if (mesh) {
  76988. wm = mesh.getWorldMatrix();
  76989. }
  76990. this._skeleton.computeAbsoluteTransforms();
  76991. var tmat = Bone._tmpMats[0];
  76992. tmat.copyFrom(this.getAbsoluteTransform());
  76993. if (mesh && wm) {
  76994. tmat.multiplyToRef(wm, tmat);
  76995. }
  76996. tmat.invert();
  76997. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76998. };
  76999. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77000. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77001. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77002. return Bone;
  77003. }(BABYLON.Node));
  77004. BABYLON.Bone = Bone;
  77005. })(BABYLON || (BABYLON = {}));
  77006. //# sourceMappingURL=babylon.bone.js.map
  77007. var BABYLON;
  77008. (function (BABYLON) {
  77009. var BoneIKController = /** @class */ (function () {
  77010. function BoneIKController(mesh, bone, options) {
  77011. this.targetPosition = BABYLON.Vector3.Zero();
  77012. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77013. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77014. this.poleAngle = 0;
  77015. this.slerpAmount = 1;
  77016. this._bone1Quat = BABYLON.Quaternion.Identity();
  77017. this._bone1Mat = BABYLON.Matrix.Identity();
  77018. this._bone2Ang = Math.PI;
  77019. this._maxAngle = Math.PI;
  77020. this._rightHandedSystem = false;
  77021. this._bendAxis = BABYLON.Vector3.Right();
  77022. this._slerping = false;
  77023. this._adjustRoll = 0;
  77024. this._bone2 = bone;
  77025. this._bone1 = bone.getParent();
  77026. if (!this._bone1) {
  77027. return;
  77028. }
  77029. this.mesh = mesh;
  77030. var bonePos = bone.getPosition();
  77031. if (bone.getAbsoluteTransform().determinant() > 0) {
  77032. this._rightHandedSystem = true;
  77033. this._bendAxis.x = 0;
  77034. this._bendAxis.y = 0;
  77035. this._bendAxis.z = -1;
  77036. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77037. this._adjustRoll = Math.PI * .5;
  77038. this._bendAxis.z = 1;
  77039. }
  77040. }
  77041. if (this._bone1.length) {
  77042. var boneScale1 = this._bone1.getAdditionalScale();
  77043. var boneScale2 = this._bone2.getAdditionalScale();
  77044. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77045. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77046. }
  77047. else if (this._bone1.children[0]) {
  77048. mesh.computeWorldMatrix(true);
  77049. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77050. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77051. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77052. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77053. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77054. }
  77055. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77056. this.maxAngle = Math.PI;
  77057. if (options) {
  77058. if (options.targetMesh) {
  77059. this.targetMesh = options.targetMesh;
  77060. this.targetMesh.computeWorldMatrix(true);
  77061. }
  77062. if (options.poleTargetMesh) {
  77063. this.poleTargetMesh = options.poleTargetMesh;
  77064. this.poleTargetMesh.computeWorldMatrix(true);
  77065. }
  77066. else if (options.poleTargetBone) {
  77067. this.poleTargetBone = options.poleTargetBone;
  77068. }
  77069. else if (this._bone1.getParent()) {
  77070. this.poleTargetBone = this._bone1.getParent();
  77071. }
  77072. if (options.poleTargetLocalOffset) {
  77073. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77074. }
  77075. if (options.poleAngle) {
  77076. this.poleAngle = options.poleAngle;
  77077. }
  77078. if (options.bendAxis) {
  77079. this._bendAxis.copyFrom(options.bendAxis);
  77080. }
  77081. if (options.maxAngle) {
  77082. this.maxAngle = options.maxAngle;
  77083. }
  77084. if (options.slerpAmount) {
  77085. this.slerpAmount = options.slerpAmount;
  77086. }
  77087. }
  77088. }
  77089. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77090. get: function () {
  77091. return this._maxAngle;
  77092. },
  77093. set: function (value) {
  77094. this._setMaxAngle(value);
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. BoneIKController.prototype._setMaxAngle = function (ang) {
  77100. if (ang < 0) {
  77101. ang = 0;
  77102. }
  77103. if (ang > Math.PI || ang == undefined) {
  77104. ang = Math.PI;
  77105. }
  77106. this._maxAngle = ang;
  77107. var a = this._bone1Length;
  77108. var b = this._bone2Length;
  77109. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77110. };
  77111. BoneIKController.prototype.update = function () {
  77112. var bone1 = this._bone1;
  77113. if (!bone1) {
  77114. return;
  77115. }
  77116. var target = this.targetPosition;
  77117. var poleTarget = this.poleTargetPosition;
  77118. var mat1 = BoneIKController._tmpMats[0];
  77119. var mat2 = BoneIKController._tmpMats[1];
  77120. if (this.targetMesh) {
  77121. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77122. }
  77123. if (this.poleTargetBone) {
  77124. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77125. }
  77126. else if (this.poleTargetMesh) {
  77127. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77128. }
  77129. var bonePos = BoneIKController._tmpVecs[0];
  77130. var zaxis = BoneIKController._tmpVecs[1];
  77131. var xaxis = BoneIKController._tmpVecs[2];
  77132. var yaxis = BoneIKController._tmpVecs[3];
  77133. var upAxis = BoneIKController._tmpVecs[4];
  77134. var _tmpQuat = BoneIKController._tmpQuat;
  77135. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77136. poleTarget.subtractToRef(bonePos, upAxis);
  77137. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77138. upAxis.y = 1;
  77139. }
  77140. else {
  77141. upAxis.normalize();
  77142. }
  77143. target.subtractToRef(bonePos, yaxis);
  77144. yaxis.normalize();
  77145. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77146. zaxis.normalize();
  77147. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77148. xaxis.normalize();
  77149. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77150. var a = this._bone1Length;
  77151. var b = this._bone2Length;
  77152. var c = BABYLON.Vector3.Distance(bonePos, target);
  77153. if (this._maxReach > 0) {
  77154. c = Math.min(this._maxReach, c);
  77155. }
  77156. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77157. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77158. if (acosa > 1) {
  77159. acosa = 1;
  77160. }
  77161. if (acosb > 1) {
  77162. acosb = 1;
  77163. }
  77164. if (acosa < -1) {
  77165. acosa = -1;
  77166. }
  77167. if (acosb < -1) {
  77168. acosb = -1;
  77169. }
  77170. var angA = Math.acos(acosa);
  77171. var angB = Math.acos(acosb);
  77172. var angC = -angA - angB;
  77173. if (this._rightHandedSystem) {
  77174. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77175. mat2.multiplyToRef(mat1, mat1);
  77176. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77177. mat2.multiplyToRef(mat1, mat1);
  77178. }
  77179. else {
  77180. var _tmpVec = BoneIKController._tmpVecs[5];
  77181. _tmpVec.copyFrom(this._bendAxis);
  77182. _tmpVec.x *= -1;
  77183. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77184. mat2.multiplyToRef(mat1, mat1);
  77185. }
  77186. if (this.poleAngle) {
  77187. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77188. mat1.multiplyToRef(mat2, mat1);
  77189. }
  77190. if (this._bone1) {
  77191. if (this.slerpAmount < 1) {
  77192. if (!this._slerping) {
  77193. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77194. }
  77195. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77196. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77197. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77198. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77199. this._slerping = true;
  77200. }
  77201. else {
  77202. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77203. this._bone1Mat.copyFrom(mat1);
  77204. this._slerping = false;
  77205. }
  77206. }
  77207. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77208. this._bone2Ang = angC;
  77209. };
  77210. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77211. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77212. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77213. return BoneIKController;
  77214. }());
  77215. BABYLON.BoneIKController = BoneIKController;
  77216. })(BABYLON || (BABYLON = {}));
  77217. //# sourceMappingURL=babylon.boneIKController.js.map
  77218. var BABYLON;
  77219. (function (BABYLON) {
  77220. var BoneLookController = /** @class */ (function () {
  77221. /**
  77222. * Create a BoneLookController
  77223. * @param mesh the mesh that the bone belongs to
  77224. * @param bone the bone that will be looking to the target
  77225. * @param target the target Vector3 to look at
  77226. * @param settings optional settings:
  77227. * - maxYaw: the maximum angle the bone will yaw to
  77228. * - minYaw: the minimum angle the bone will yaw to
  77229. * - maxPitch: the maximum angle the bone will pitch to
  77230. * - minPitch: the minimum angle the bone will yaw to
  77231. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77232. * - upAxis: the up axis of the coordinate system
  77233. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77234. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  77235. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77236. * - adjustYaw: used to make an adjustment to the yaw of the bone
  77237. * - adjustPitch: used to make an adjustment to the pitch of the bone
  77238. * - adjustRoll: used to make an adjustment to the roll of the bone
  77239. **/
  77240. function BoneLookController(mesh, bone, target, options) {
  77241. /**
  77242. * The up axis of the coordinate system that is used when the bone is rotated.
  77243. */
  77244. this.upAxis = BABYLON.Vector3.Up();
  77245. /**
  77246. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77247. */
  77248. this.upAxisSpace = BABYLON.Space.LOCAL;
  77249. /**
  77250. * Used to make an adjustment to the yaw of the bone.
  77251. */
  77252. this.adjustYaw = 0;
  77253. /**
  77254. * Used to make an adjustment to the pitch of the bone.
  77255. */
  77256. this.adjustPitch = 0;
  77257. /**
  77258. * Used to make an adjustment to the roll of the bone.
  77259. */
  77260. this.adjustRoll = 0;
  77261. /**
  77262. * 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).
  77263. */
  77264. this.slerpAmount = 1;
  77265. this._boneQuat = BABYLON.Quaternion.Identity();
  77266. this._slerping = false;
  77267. this._firstFrameSkipped = false;
  77268. this._fowardAxis = BABYLON.Vector3.Forward();
  77269. this.mesh = mesh;
  77270. this.bone = bone;
  77271. this.target = target;
  77272. if (options) {
  77273. if (options.adjustYaw) {
  77274. this.adjustYaw = options.adjustYaw;
  77275. }
  77276. if (options.adjustPitch) {
  77277. this.adjustPitch = options.adjustPitch;
  77278. }
  77279. if (options.adjustRoll) {
  77280. this.adjustRoll = options.adjustRoll;
  77281. }
  77282. if (options.maxYaw != null) {
  77283. this.maxYaw = options.maxYaw;
  77284. }
  77285. else {
  77286. this.maxYaw = Math.PI;
  77287. }
  77288. if (options.minYaw != null) {
  77289. this.minYaw = options.minYaw;
  77290. }
  77291. else {
  77292. this.minYaw = -Math.PI;
  77293. }
  77294. if (options.maxPitch != null) {
  77295. this.maxPitch = options.maxPitch;
  77296. }
  77297. else {
  77298. this.maxPitch = Math.PI;
  77299. }
  77300. if (options.minPitch != null) {
  77301. this.minPitch = options.minPitch;
  77302. }
  77303. else {
  77304. this.minPitch = -Math.PI;
  77305. }
  77306. if (options.slerpAmount != null) {
  77307. this.slerpAmount = options.slerpAmount;
  77308. }
  77309. if (options.upAxis != null) {
  77310. this.upAxis = options.upAxis;
  77311. }
  77312. if (options.upAxisSpace != null) {
  77313. this.upAxisSpace = options.upAxisSpace;
  77314. }
  77315. if (options.yawAxis != null || options.pitchAxis != null) {
  77316. var newYawAxis = BABYLON.Axis.Y;
  77317. var newPitchAxis = BABYLON.Axis.X;
  77318. if (options.yawAxis != null) {
  77319. newYawAxis = options.yawAxis.clone();
  77320. newYawAxis.normalize();
  77321. }
  77322. if (options.pitchAxis != null) {
  77323. newPitchAxis = options.pitchAxis.clone();
  77324. newPitchAxis.normalize();
  77325. }
  77326. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77327. this._transformYawPitch = BABYLON.Matrix.Identity();
  77328. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77329. this._transformYawPitchInv = this._transformYawPitch.clone();
  77330. this._transformYawPitch.invert();
  77331. }
  77332. }
  77333. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77334. this.upAxisSpace = BABYLON.Space.LOCAL;
  77335. }
  77336. }
  77337. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77338. /**
  77339. * Get/set the minimum yaw angle that the bone can look to.
  77340. */
  77341. get: function () {
  77342. return this._minYaw;
  77343. },
  77344. set: function (value) {
  77345. this._minYaw = value;
  77346. this._minYawSin = Math.sin(value);
  77347. this._minYawCos = Math.cos(value);
  77348. if (this._maxYaw != null) {
  77349. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77350. this._yawRange = this._maxYaw - this._minYaw;
  77351. }
  77352. },
  77353. enumerable: true,
  77354. configurable: true
  77355. });
  77356. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77357. /**
  77358. * Get/set the maximum yaw angle that the bone can look to.
  77359. */
  77360. get: function () {
  77361. return this._maxYaw;
  77362. },
  77363. set: function (value) {
  77364. this._maxYaw = value;
  77365. this._maxYawSin = Math.sin(value);
  77366. this._maxYawCos = Math.cos(value);
  77367. if (this._minYaw != null) {
  77368. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77369. this._yawRange = this._maxYaw - this._minYaw;
  77370. }
  77371. },
  77372. enumerable: true,
  77373. configurable: true
  77374. });
  77375. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77376. /**
  77377. * Get/set the minimum pitch angle that the bone can look to.
  77378. */
  77379. get: function () {
  77380. return this._minPitch;
  77381. },
  77382. set: function (value) {
  77383. this._minPitch = value;
  77384. this._minPitchTan = Math.tan(value);
  77385. },
  77386. enumerable: true,
  77387. configurable: true
  77388. });
  77389. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77390. /**
  77391. * Get/set the maximum pitch angle that the bone can look to.
  77392. */
  77393. get: function () {
  77394. return this._maxPitch;
  77395. },
  77396. set: function (value) {
  77397. this._maxPitch = value;
  77398. this._maxPitchTan = Math.tan(value);
  77399. },
  77400. enumerable: true,
  77401. configurable: true
  77402. });
  77403. /**
  77404. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  77405. */
  77406. BoneLookController.prototype.update = function () {
  77407. //skip the first frame when slerping so that the mesh rotation is correct
  77408. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77409. this._firstFrameSkipped = true;
  77410. return;
  77411. }
  77412. var bone = this.bone;
  77413. var bonePos = BoneLookController._tmpVecs[0];
  77414. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77415. var target = this.target;
  77416. var _tmpMat1 = BoneLookController._tmpMats[0];
  77417. var _tmpMat2 = BoneLookController._tmpMats[1];
  77418. var mesh = this.mesh;
  77419. var parentBone = bone.getParent();
  77420. var upAxis = BoneLookController._tmpVecs[1];
  77421. upAxis.copyFrom(this.upAxis);
  77422. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77423. if (this._transformYawPitch) {
  77424. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77425. }
  77426. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77427. }
  77428. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77429. mesh.getDirectionToRef(upAxis, upAxis);
  77430. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77431. upAxis.normalize();
  77432. }
  77433. }
  77434. var checkYaw = false;
  77435. var checkPitch = false;
  77436. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  77437. checkYaw = true;
  77438. }
  77439. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  77440. checkPitch = true;
  77441. }
  77442. if (checkYaw || checkPitch) {
  77443. var spaceMat = BoneLookController._tmpMats[2];
  77444. var spaceMatInv = BoneLookController._tmpMats[3];
  77445. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  77446. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  77447. }
  77448. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  77449. spaceMat.copyFrom(mesh.getWorldMatrix());
  77450. }
  77451. else {
  77452. var forwardAxis = BoneLookController._tmpVecs[2];
  77453. forwardAxis.copyFrom(this._fowardAxis);
  77454. if (this._transformYawPitch) {
  77455. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  77456. }
  77457. if (parentBone) {
  77458. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  77459. }
  77460. else {
  77461. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  77462. }
  77463. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  77464. rightAxis.normalize();
  77465. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  77466. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  77467. }
  77468. spaceMat.invertToRef(spaceMatInv);
  77469. var xzlen = null;
  77470. if (checkPitch) {
  77471. var localTarget = BoneLookController._tmpVecs[3];
  77472. target.subtractToRef(bonePos, localTarget);
  77473. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77474. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77475. var pitch = Math.atan2(localTarget.y, xzlen);
  77476. var newPitch = pitch;
  77477. if (pitch > this._maxPitch) {
  77478. localTarget.y = this._maxPitchTan * xzlen;
  77479. newPitch = this._maxPitch;
  77480. }
  77481. else if (pitch < this._minPitch) {
  77482. localTarget.y = this._minPitchTan * xzlen;
  77483. newPitch = this._minPitch;
  77484. }
  77485. if (pitch != newPitch) {
  77486. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77487. localTarget.addInPlace(bonePos);
  77488. target = localTarget;
  77489. }
  77490. }
  77491. if (checkYaw) {
  77492. var localTarget = BoneLookController._tmpVecs[4];
  77493. target.subtractToRef(bonePos, localTarget);
  77494. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77495. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77496. var newYaw = yaw;
  77497. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77498. if (xzlen == null) {
  77499. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77500. }
  77501. if (this._yawRange > Math.PI) {
  77502. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77503. localTarget.z = this._maxYawCos * xzlen;
  77504. localTarget.x = this._maxYawSin * xzlen;
  77505. newYaw = this._maxYaw;
  77506. }
  77507. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77508. localTarget.z = this._minYawCos * xzlen;
  77509. localTarget.x = this._minYawSin * xzlen;
  77510. newYaw = this._minYaw;
  77511. }
  77512. }
  77513. else {
  77514. if (yaw > this._maxYaw) {
  77515. localTarget.z = this._maxYawCos * xzlen;
  77516. localTarget.x = this._maxYawSin * xzlen;
  77517. newYaw = this._maxYaw;
  77518. }
  77519. else if (yaw < this._minYaw) {
  77520. localTarget.z = this._minYawCos * xzlen;
  77521. localTarget.x = this._minYawSin * xzlen;
  77522. newYaw = this._minYaw;
  77523. }
  77524. }
  77525. }
  77526. if (this._slerping && this._yawRange > Math.PI) {
  77527. //are we going to be crossing into the min/max region?
  77528. var boneFwd = BoneLookController._tmpVecs[8];
  77529. boneFwd.copyFrom(BABYLON.Axis.Z);
  77530. if (this._transformYawPitch) {
  77531. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77532. }
  77533. var boneRotMat = BoneLookController._tmpMats[4];
  77534. this._boneQuat.toRotationMatrix(boneRotMat);
  77535. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77536. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77537. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77538. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77539. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77540. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77541. if (angBtwTar > angBtwMidYaw) {
  77542. if (xzlen == null) {
  77543. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77544. }
  77545. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77546. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77547. if (angBtwMin < angBtwMax) {
  77548. newYaw = boneYaw + Math.PI * .75;
  77549. localTarget.z = Math.cos(newYaw) * xzlen;
  77550. localTarget.x = Math.sin(newYaw) * xzlen;
  77551. }
  77552. else {
  77553. newYaw = boneYaw - Math.PI * .75;
  77554. localTarget.z = Math.cos(newYaw) * xzlen;
  77555. localTarget.x = Math.sin(newYaw) * xzlen;
  77556. }
  77557. }
  77558. }
  77559. if (yaw != newYaw) {
  77560. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77561. localTarget.addInPlace(bonePos);
  77562. target = localTarget;
  77563. }
  77564. }
  77565. }
  77566. var zaxis = BoneLookController._tmpVecs[5];
  77567. var xaxis = BoneLookController._tmpVecs[6];
  77568. var yaxis = BoneLookController._tmpVecs[7];
  77569. var _tmpQuat = BoneLookController._tmpQuat;
  77570. target.subtractToRef(bonePos, zaxis);
  77571. zaxis.normalize();
  77572. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77573. xaxis.normalize();
  77574. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77575. yaxis.normalize();
  77576. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77577. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77578. return;
  77579. }
  77580. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77581. return;
  77582. }
  77583. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77584. return;
  77585. }
  77586. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77587. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77588. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77589. }
  77590. if (this.slerpAmount < 1) {
  77591. if (!this._slerping) {
  77592. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77593. }
  77594. if (this._transformYawPitch) {
  77595. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77596. }
  77597. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77598. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77599. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77600. this._slerping = true;
  77601. }
  77602. else {
  77603. if (this._transformYawPitch) {
  77604. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77605. }
  77606. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77607. this._slerping = false;
  77608. }
  77609. };
  77610. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77611. var angDiff = ang2 - ang1;
  77612. angDiff %= Math.PI * 2;
  77613. if (angDiff > Math.PI) {
  77614. angDiff -= Math.PI * 2;
  77615. }
  77616. else if (angDiff < -Math.PI) {
  77617. angDiff += Math.PI * 2;
  77618. }
  77619. return angDiff;
  77620. };
  77621. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77622. ang1 %= (2 * Math.PI);
  77623. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77624. ang2 %= (2 * Math.PI);
  77625. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77626. var ab = 0;
  77627. if (ang1 < ang2) {
  77628. ab = ang2 - ang1;
  77629. }
  77630. else {
  77631. ab = ang1 - ang2;
  77632. }
  77633. if (ab > Math.PI) {
  77634. ab = Math.PI * 2 - ab;
  77635. }
  77636. return ab;
  77637. };
  77638. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77639. ang %= (2 * Math.PI);
  77640. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77641. ang1 %= (2 * Math.PI);
  77642. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77643. ang2 %= (2 * Math.PI);
  77644. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77645. if (ang1 < ang2) {
  77646. if (ang > ang1 && ang < ang2) {
  77647. return true;
  77648. }
  77649. }
  77650. else {
  77651. if (ang > ang2 && ang < ang1) {
  77652. return true;
  77653. }
  77654. }
  77655. return false;
  77656. };
  77657. 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()];
  77658. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77659. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77660. return BoneLookController;
  77661. }());
  77662. BABYLON.BoneLookController = BoneLookController;
  77663. })(BABYLON || (BABYLON = {}));
  77664. //# sourceMappingURL=babylon.boneLookController.js.map
  77665. var BABYLON;
  77666. (function (BABYLON) {
  77667. var Skeleton = /** @class */ (function () {
  77668. function Skeleton(name, id, scene) {
  77669. this.name = name;
  77670. this.id = id;
  77671. this.bones = new Array();
  77672. this.needInitialSkinMatrix = false;
  77673. this._isDirty = true;
  77674. this._meshesWithPoseMatrix = new Array();
  77675. this._identity = BABYLON.Matrix.Identity();
  77676. this._ranges = {};
  77677. this._lastAbsoluteTransformsUpdateId = -1;
  77678. /**
  77679. * Specifies if the skeleton should be serialized.
  77680. */
  77681. this.doNotSerialize = false;
  77682. this._animationPropertiesOverride = null;
  77683. // Events
  77684. /**
  77685. * An event triggered before computing the skeleton's matrices
  77686. */
  77687. this.onBeforeComputeObservable = new BABYLON.Observable();
  77688. this.bones = [];
  77689. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77690. scene.skeletons.push(this);
  77691. //make sure it will recalculate the matrix next time prepare is called.
  77692. this._isDirty = true;
  77693. }
  77694. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  77695. /**
  77696. * Gets or sets the animation properties override
  77697. */
  77698. get: function () {
  77699. if (!this._animationPropertiesOverride) {
  77700. return this._scene.animationPropertiesOverride;
  77701. }
  77702. return this._animationPropertiesOverride;
  77703. },
  77704. set: function (value) {
  77705. this._animationPropertiesOverride = value;
  77706. },
  77707. enumerable: true,
  77708. configurable: true
  77709. });
  77710. // Members
  77711. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77712. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77713. return mesh._bonesTransformMatrices;
  77714. }
  77715. if (!this._transformMatrices) {
  77716. this.prepare();
  77717. }
  77718. return this._transformMatrices;
  77719. };
  77720. Skeleton.prototype.getScene = function () {
  77721. return this._scene;
  77722. };
  77723. // Methods
  77724. /**
  77725. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77726. */
  77727. Skeleton.prototype.toString = function (fullDetails) {
  77728. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77729. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77730. if (fullDetails) {
  77731. ret += ", Ranges: {";
  77732. var first = true;
  77733. for (var name_1 in this._ranges) {
  77734. if (first) {
  77735. ret += ", ";
  77736. first = false;
  77737. }
  77738. ret += name_1;
  77739. }
  77740. ret += "}";
  77741. }
  77742. return ret;
  77743. };
  77744. /**
  77745. * Get bone's index searching by name
  77746. * @param {string} name is bone's name to search for
  77747. * @return {number} Indice of the bone. Returns -1 if not found
  77748. */
  77749. Skeleton.prototype.getBoneIndexByName = function (name) {
  77750. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77751. if (this.bones[boneIndex].name === name) {
  77752. return boneIndex;
  77753. }
  77754. }
  77755. return -1;
  77756. };
  77757. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77758. // check name not already in use
  77759. if (!this._ranges[name]) {
  77760. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77761. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77762. if (this.bones[i].animations[0]) {
  77763. this.bones[i].animations[0].createRange(name, from, to);
  77764. }
  77765. }
  77766. }
  77767. };
  77768. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77769. if (deleteFrames === void 0) { deleteFrames = true; }
  77770. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77771. if (this.bones[i].animations[0]) {
  77772. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77773. }
  77774. }
  77775. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77776. };
  77777. Skeleton.prototype.getAnimationRange = function (name) {
  77778. return this._ranges[name];
  77779. };
  77780. /**
  77781. * Returns as an Array, all AnimationRanges defined on this skeleton
  77782. */
  77783. Skeleton.prototype.getAnimationRanges = function () {
  77784. var animationRanges = [];
  77785. var name;
  77786. var i = 0;
  77787. for (name in this._ranges) {
  77788. animationRanges[i] = this._ranges[name];
  77789. i++;
  77790. }
  77791. return animationRanges;
  77792. };
  77793. /**
  77794. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77795. */
  77796. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77797. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77798. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77799. return false;
  77800. }
  77801. var ret = true;
  77802. var frameOffset = this._getHighestAnimationFrame() + 1;
  77803. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77804. var boneDict = {};
  77805. var sourceBones = source.bones;
  77806. var nBones;
  77807. var i;
  77808. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77809. boneDict[sourceBones[i].name] = sourceBones[i];
  77810. }
  77811. if (this.bones.length !== sourceBones.length) {
  77812. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77813. ret = false;
  77814. }
  77815. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77816. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77817. var boneName = this.bones[i].name;
  77818. var sourceBone = boneDict[boneName];
  77819. if (sourceBone) {
  77820. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77821. }
  77822. else {
  77823. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77824. ret = false;
  77825. }
  77826. }
  77827. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77828. var range = source.getAnimationRange(name);
  77829. if (range) {
  77830. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77831. }
  77832. return ret;
  77833. };
  77834. Skeleton.prototype.returnToRest = function () {
  77835. for (var index = 0; index < this.bones.length; index++) {
  77836. this.bones[index].returnToRest();
  77837. }
  77838. };
  77839. Skeleton.prototype._getHighestAnimationFrame = function () {
  77840. var ret = 0;
  77841. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77842. if (this.bones[i].animations[0]) {
  77843. var highest = this.bones[i].animations[0].getHighestFrame();
  77844. if (ret < highest) {
  77845. ret = highest;
  77846. }
  77847. }
  77848. }
  77849. return ret;
  77850. };
  77851. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77852. var range = this.getAnimationRange(name);
  77853. if (!range) {
  77854. return null;
  77855. }
  77856. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77857. };
  77858. Skeleton.prototype._markAsDirty = function () {
  77859. this._isDirty = true;
  77860. };
  77861. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77862. this._meshesWithPoseMatrix.push(mesh);
  77863. };
  77864. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77865. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77866. if (index > -1) {
  77867. this._meshesWithPoseMatrix.splice(index, 1);
  77868. }
  77869. };
  77870. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77871. this.onBeforeComputeObservable.notifyObservers(this);
  77872. for (var index = 0; index < this.bones.length; index++) {
  77873. var bone = this.bones[index];
  77874. var parentBone = bone.getParent();
  77875. if (parentBone) {
  77876. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77877. }
  77878. else {
  77879. if (initialSkinMatrix) {
  77880. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77881. }
  77882. else {
  77883. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77884. }
  77885. }
  77886. if (bone._index !== -1) {
  77887. var mappedIndex = bone._index === null ? index : bone._index;
  77888. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77889. }
  77890. }
  77891. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77892. };
  77893. Skeleton.prototype.prepare = function () {
  77894. if (!this._isDirty) {
  77895. return;
  77896. }
  77897. if (this.needInitialSkinMatrix) {
  77898. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77899. var mesh = this._meshesWithPoseMatrix[index];
  77900. var poseMatrix = mesh.getPoseMatrix();
  77901. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77902. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77903. }
  77904. if (this._synchronizedWithMesh !== mesh) {
  77905. this._synchronizedWithMesh = mesh;
  77906. // Prepare bones
  77907. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77908. var bone = this.bones[boneIndex];
  77909. if (!bone.getParent()) {
  77910. var matrix = bone.getBaseMatrix();
  77911. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77912. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77913. }
  77914. }
  77915. }
  77916. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77917. }
  77918. }
  77919. else {
  77920. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77921. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77922. }
  77923. this._computeTransformMatrices(this._transformMatrices, null);
  77924. }
  77925. this._isDirty = false;
  77926. this._scene._activeBones.addCount(this.bones.length, false);
  77927. };
  77928. Skeleton.prototype.getAnimatables = function () {
  77929. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77930. this._animatables = [];
  77931. for (var index = 0; index < this.bones.length; index++) {
  77932. this._animatables.push(this.bones[index]);
  77933. }
  77934. }
  77935. return this._animatables;
  77936. };
  77937. Skeleton.prototype.clone = function (name, id) {
  77938. var result = new Skeleton(name, id || name, this._scene);
  77939. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77940. for (var index = 0; index < this.bones.length; index++) {
  77941. var source = this.bones[index];
  77942. var parentBone = null;
  77943. var parent_1 = source.getParent();
  77944. if (parent_1) {
  77945. var parentIndex = this.bones.indexOf(parent_1);
  77946. parentBone = result.bones[parentIndex];
  77947. }
  77948. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77949. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77950. }
  77951. if (this._ranges) {
  77952. result._ranges = {};
  77953. for (var rangeName in this._ranges) {
  77954. var range = this._ranges[rangeName];
  77955. if (range) {
  77956. result._ranges[rangeName] = range.clone();
  77957. }
  77958. }
  77959. }
  77960. this._isDirty = true;
  77961. return result;
  77962. };
  77963. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77964. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77965. this.bones.forEach(function (bone) {
  77966. bone.animations.forEach(function (animation) {
  77967. animation.enableBlending = true;
  77968. animation.blendingSpeed = blendingSpeed;
  77969. });
  77970. });
  77971. };
  77972. Skeleton.prototype.dispose = function () {
  77973. this._meshesWithPoseMatrix = [];
  77974. // Animations
  77975. this.getScene().stopAnimation(this);
  77976. // Remove from scene
  77977. this.getScene().removeSkeleton(this);
  77978. };
  77979. Skeleton.prototype.serialize = function () {
  77980. var serializationObject = {};
  77981. serializationObject.name = this.name;
  77982. serializationObject.id = this.id;
  77983. if (this.dimensionsAtRest) {
  77984. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77985. }
  77986. serializationObject.bones = [];
  77987. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77988. for (var index = 0; index < this.bones.length; index++) {
  77989. var bone = this.bones[index];
  77990. var parent_2 = bone.getParent();
  77991. var serializedBone = {
  77992. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77993. name: bone.name,
  77994. matrix: bone.getBaseMatrix().toArray(),
  77995. rest: bone.getRestPose().toArray()
  77996. };
  77997. serializationObject.bones.push(serializedBone);
  77998. if (bone.length) {
  77999. serializedBone.length = bone.length;
  78000. }
  78001. if (bone.animations && bone.animations.length > 0) {
  78002. serializedBone.animation = bone.animations[0].serialize();
  78003. }
  78004. serializationObject.ranges = [];
  78005. for (var name in this._ranges) {
  78006. var source = this._ranges[name];
  78007. if (!source) {
  78008. continue;
  78009. }
  78010. var range = {};
  78011. range.name = name;
  78012. range.from = source.from;
  78013. range.to = source.to;
  78014. serializationObject.ranges.push(range);
  78015. }
  78016. }
  78017. return serializationObject;
  78018. };
  78019. Skeleton.Parse = function (parsedSkeleton, scene) {
  78020. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78021. if (parsedSkeleton.dimensionsAtRest) {
  78022. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78023. }
  78024. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78025. var index;
  78026. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78027. var parsedBone = parsedSkeleton.bones[index];
  78028. var parentBone = null;
  78029. if (parsedBone.parentBoneIndex > -1) {
  78030. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78031. }
  78032. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78033. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78034. if (parsedBone.length) {
  78035. bone.length = parsedBone.length;
  78036. }
  78037. if (parsedBone.animation) {
  78038. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78039. }
  78040. }
  78041. // placed after bones, so createAnimationRange can cascade down
  78042. if (parsedSkeleton.ranges) {
  78043. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78044. var data = parsedSkeleton.ranges[index];
  78045. skeleton.createAnimationRange(data.name, data.from, data.to);
  78046. }
  78047. }
  78048. return skeleton;
  78049. };
  78050. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78051. if (forceUpdate === void 0) { forceUpdate = false; }
  78052. var renderId = this._scene.getRenderId();
  78053. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78054. this.bones[0].computeAbsoluteTransforms();
  78055. this._lastAbsoluteTransformsUpdateId = renderId;
  78056. }
  78057. };
  78058. Skeleton.prototype.getPoseMatrix = function () {
  78059. var poseMatrix = null;
  78060. if (this._meshesWithPoseMatrix.length > 0) {
  78061. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78062. }
  78063. return poseMatrix;
  78064. };
  78065. Skeleton.prototype.sortBones = function () {
  78066. var bones = new Array();
  78067. var visited = new Array(this.bones.length);
  78068. for (var index = 0; index < this.bones.length; index++) {
  78069. this._sortBones(index, bones, visited);
  78070. }
  78071. this.bones = bones;
  78072. };
  78073. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78074. if (visited[index]) {
  78075. return;
  78076. }
  78077. visited[index] = true;
  78078. var bone = this.bones[index];
  78079. if (bone._index === undefined) {
  78080. bone._index = index;
  78081. }
  78082. var parentBone = bone.getParent();
  78083. if (parentBone) {
  78084. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78085. }
  78086. bones.push(bone);
  78087. };
  78088. return Skeleton;
  78089. }());
  78090. BABYLON.Skeleton = Skeleton;
  78091. })(BABYLON || (BABYLON = {}));
  78092. //# sourceMappingURL=babylon.skeleton.js.map
  78093. var BABYLON;
  78094. (function (BABYLON) {
  78095. var SphericalPolynomial = /** @class */ (function () {
  78096. function SphericalPolynomial() {
  78097. this.x = BABYLON.Vector3.Zero();
  78098. this.y = BABYLON.Vector3.Zero();
  78099. this.z = BABYLON.Vector3.Zero();
  78100. this.xx = BABYLON.Vector3.Zero();
  78101. this.yy = BABYLON.Vector3.Zero();
  78102. this.zz = BABYLON.Vector3.Zero();
  78103. this.xy = BABYLON.Vector3.Zero();
  78104. this.yz = BABYLON.Vector3.Zero();
  78105. this.zx = BABYLON.Vector3.Zero();
  78106. }
  78107. SphericalPolynomial.prototype.addAmbient = function (color) {
  78108. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78109. this.xx = this.xx.add(colorVector);
  78110. this.yy = this.yy.add(colorVector);
  78111. this.zz = this.zz.add(colorVector);
  78112. };
  78113. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78114. var result = new SphericalPolynomial();
  78115. result.x = harmonics.L11.scale(1.02333);
  78116. result.y = harmonics.L1_1.scale(1.02333);
  78117. result.z = harmonics.L10.scale(1.02333);
  78118. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78119. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78120. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78121. result.yz = harmonics.L2_1.scale(0.858086);
  78122. result.zx = harmonics.L21.scale(0.858086);
  78123. result.xy = harmonics.L2_2.scale(0.858086);
  78124. result.scale(1.0 / Math.PI);
  78125. return result;
  78126. };
  78127. SphericalPolynomial.prototype.scale = function (scale) {
  78128. this.x = this.x.scale(scale);
  78129. this.y = this.y.scale(scale);
  78130. this.z = this.z.scale(scale);
  78131. this.xx = this.xx.scale(scale);
  78132. this.yy = this.yy.scale(scale);
  78133. this.zz = this.zz.scale(scale);
  78134. this.yz = this.yz.scale(scale);
  78135. this.zx = this.zx.scale(scale);
  78136. this.xy = this.xy.scale(scale);
  78137. };
  78138. return SphericalPolynomial;
  78139. }());
  78140. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78141. var SphericalHarmonics = /** @class */ (function () {
  78142. function SphericalHarmonics() {
  78143. this.L00 = BABYLON.Vector3.Zero();
  78144. this.L1_1 = BABYLON.Vector3.Zero();
  78145. this.L10 = BABYLON.Vector3.Zero();
  78146. this.L11 = BABYLON.Vector3.Zero();
  78147. this.L2_2 = BABYLON.Vector3.Zero();
  78148. this.L2_1 = BABYLON.Vector3.Zero();
  78149. this.L20 = BABYLON.Vector3.Zero();
  78150. this.L21 = BABYLON.Vector3.Zero();
  78151. this.L22 = BABYLON.Vector3.Zero();
  78152. }
  78153. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78154. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78155. var c = colorVector.scale(deltaSolidAngle);
  78156. this.L00 = this.L00.add(c.scale(0.282095));
  78157. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78158. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78159. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78160. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78161. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78162. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78163. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78164. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78165. };
  78166. SphericalHarmonics.prototype.scale = function (scale) {
  78167. this.L00 = this.L00.scale(scale);
  78168. this.L1_1 = this.L1_1.scale(scale);
  78169. this.L10 = this.L10.scale(scale);
  78170. this.L11 = this.L11.scale(scale);
  78171. this.L2_2 = this.L2_2.scale(scale);
  78172. this.L2_1 = this.L2_1.scale(scale);
  78173. this.L20 = this.L20.scale(scale);
  78174. this.L21 = this.L21.scale(scale);
  78175. this.L22 = this.L22.scale(scale);
  78176. };
  78177. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78178. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78179. //
  78180. // E_lm = A_l * L_lm
  78181. //
  78182. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78183. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78184. // the scaling factors are given in equation 9.
  78185. // Constant (Band 0)
  78186. this.L00 = this.L00.scale(3.141593);
  78187. // Linear (Band 1)
  78188. this.L1_1 = this.L1_1.scale(2.094395);
  78189. this.L10 = this.L10.scale(2.094395);
  78190. this.L11 = this.L11.scale(2.094395);
  78191. // Quadratic (Band 2)
  78192. this.L2_2 = this.L2_2.scale(0.785398);
  78193. this.L2_1 = this.L2_1.scale(0.785398);
  78194. this.L20 = this.L20.scale(0.785398);
  78195. this.L21 = this.L21.scale(0.785398);
  78196. this.L22 = this.L22.scale(0.785398);
  78197. };
  78198. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78199. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78200. // L = (1/pi) * E * rho
  78201. //
  78202. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78203. this.scale(1.0 / Math.PI);
  78204. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78205. // (The pixel shader must apply albedo after texture fetches, etc).
  78206. };
  78207. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78208. var result = new SphericalHarmonics();
  78209. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78210. result.L1_1 = polynomial.y.scale(0.977204);
  78211. result.L10 = polynomial.z.scale(0.977204);
  78212. result.L11 = polynomial.x.scale(0.977204);
  78213. result.L2_2 = polynomial.xy.scale(1.16538);
  78214. result.L2_1 = polynomial.yz.scale(1.16538);
  78215. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  78216. result.L21 = polynomial.zx.scale(1.16538);
  78217. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  78218. result.scale(Math.PI);
  78219. return result;
  78220. };
  78221. return SphericalHarmonics;
  78222. }());
  78223. BABYLON.SphericalHarmonics = SphericalHarmonics;
  78224. })(BABYLON || (BABYLON = {}));
  78225. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78226. var BABYLON;
  78227. (function (BABYLON) {
  78228. var FileFaceOrientation = /** @class */ (function () {
  78229. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78230. this.name = name;
  78231. this.worldAxisForNormal = worldAxisForNormal;
  78232. this.worldAxisForFileX = worldAxisForFileX;
  78233. this.worldAxisForFileY = worldAxisForFileY;
  78234. }
  78235. return FileFaceOrientation;
  78236. }());
  78237. ;
  78238. /**
  78239. * Helper class dealing with the extraction of spherical polynomial dataArray
  78240. * from a cube map.
  78241. */
  78242. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78243. function CubeMapToSphericalPolynomialTools() {
  78244. }
  78245. /**
  78246. * Converts a texture to the according Spherical Polynomial data.
  78247. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78248. *
  78249. * @param texture The texture to extract the information from.
  78250. * @return The Spherical Polynomial data.
  78251. */
  78252. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78253. if (!texture.isCube) {
  78254. // Only supports cube Textures currently.
  78255. return null;
  78256. }
  78257. var size = texture.getSize().width;
  78258. var right = texture.readPixels(0);
  78259. var left = texture.readPixels(1);
  78260. var up;
  78261. var down;
  78262. if (texture.isRenderTarget) {
  78263. up = texture.readPixels(3);
  78264. down = texture.readPixels(2);
  78265. }
  78266. else {
  78267. up = texture.readPixels(2);
  78268. down = texture.readPixels(3);
  78269. }
  78270. var front = texture.readPixels(4);
  78271. var back = texture.readPixels(5);
  78272. var gammaSpace = texture.gammaSpace;
  78273. // Always read as RGBA.
  78274. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78275. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78276. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78277. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78278. }
  78279. var cubeInfo = {
  78280. size: size,
  78281. right: right,
  78282. left: left,
  78283. up: up,
  78284. down: down,
  78285. front: front,
  78286. back: back,
  78287. format: format,
  78288. type: type,
  78289. gammaSpace: gammaSpace,
  78290. };
  78291. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78292. };
  78293. /**
  78294. * Converts a cubemap to the according Spherical Polynomial data.
  78295. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78296. *
  78297. * @param cubeInfo The Cube map to extract the information from.
  78298. * @return The Spherical Polynomial data.
  78299. */
  78300. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78301. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78302. var totalSolidAngle = 0.0;
  78303. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78304. var du = 2.0 / cubeInfo.size;
  78305. var dv = du;
  78306. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78307. var minUV = du * 0.5 - 1.0;
  78308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78309. var fileFace = this.FileFaces[faceIndex];
  78310. var dataArray = cubeInfo[fileFace.name];
  78311. var v = minUV;
  78312. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78313. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78314. // Because SP is still linear, so summation is fine in that basis.
  78315. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78316. for (var y = 0; y < cubeInfo.size; y++) {
  78317. var u = minUV;
  78318. for (var x = 0; x < cubeInfo.size; x++) {
  78319. // World direction (not normalised)
  78320. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78321. worldDirection.normalize();
  78322. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  78323. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  78324. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  78325. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  78326. // Handle Integer types.
  78327. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78328. r /= 255;
  78329. g /= 255;
  78330. b /= 255;
  78331. }
  78332. // Handle Gamma space textures.
  78333. if (cubeInfo.gammaSpace) {
  78334. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  78335. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  78336. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  78337. }
  78338. var color = new BABYLON.Color3(r, g, b);
  78339. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  78340. totalSolidAngle += deltaSolidAngle;
  78341. u += du;
  78342. }
  78343. v += dv;
  78344. }
  78345. }
  78346. // Solid angle for entire sphere is 4*pi
  78347. var sphereSolidAngle = 4.0 * Math.PI;
  78348. // Adjust the solid angle to allow for how many faces we processed.
  78349. var facesProcessed = 6.0;
  78350. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  78351. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  78352. // This is needed because the numerical integration over the cube uses a
  78353. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  78354. // and also to compensate for accumulative error due to float precision in the summation.
  78355. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  78356. sphericalHarmonics.scale(correctionFactor);
  78357. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  78358. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  78359. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  78360. };
  78361. CubeMapToSphericalPolynomialTools.FileFaces = [
  78362. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  78363. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  78364. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  78365. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  78366. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  78367. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  78368. ];
  78369. return CubeMapToSphericalPolynomialTools;
  78370. }());
  78371. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  78372. })(BABYLON || (BABYLON = {}));
  78373. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  78374. var BABYLON;
  78375. (function (BABYLON) {
  78376. /**
  78377. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  78378. */
  78379. var PanoramaToCubeMapTools = /** @class */ (function () {
  78380. function PanoramaToCubeMapTools() {
  78381. }
  78382. /**
  78383. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  78384. *
  78385. * @param float32Array The source data.
  78386. * @param inputWidth The width of the input panorama.
  78387. * @param inputhHeight The height of the input panorama.
  78388. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  78389. * @return The cubemap data
  78390. */
  78391. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  78392. if (!float32Array) {
  78393. throw "ConvertPanoramaToCubemap: input cannot be null";
  78394. }
  78395. if (float32Array.length != inputWidth * inputHeight * 3) {
  78396. throw "ConvertPanoramaToCubemap: input size is wrong";
  78397. }
  78398. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  78399. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  78400. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  78401. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  78402. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  78403. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  78404. return {
  78405. front: textureFront,
  78406. back: textureBack,
  78407. left: textureLeft,
  78408. right: textureRight,
  78409. up: textureUp,
  78410. down: textureDown,
  78411. size: size,
  78412. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  78413. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  78414. gammaSpace: false,
  78415. };
  78416. };
  78417. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  78418. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  78419. var textureArray = new Float32Array(buffer);
  78420. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  78421. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  78422. var dy = 1 / texSize;
  78423. var fy = 0;
  78424. for (var y = 0; y < texSize; y++) {
  78425. var xv1 = faceData[0];
  78426. var xv2 = faceData[2];
  78427. for (var x = 0; x < texSize; x++) {
  78428. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  78429. v.normalize();
  78430. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  78431. // 3 channels per pixels
  78432. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  78433. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  78434. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  78435. xv1 = xv1.add(rotDX1);
  78436. xv2 = xv2.add(rotDX2);
  78437. }
  78438. fy += dy;
  78439. }
  78440. return textureArray;
  78441. };
  78442. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  78443. var theta = Math.atan2(vDir.z, vDir.x);
  78444. var phi = Math.acos(vDir.y);
  78445. while (theta < -Math.PI)
  78446. theta += 2 * Math.PI;
  78447. while (theta > Math.PI)
  78448. theta -= 2 * Math.PI;
  78449. var dx = theta / Math.PI;
  78450. var dy = phi / Math.PI;
  78451. // recenter.
  78452. dx = dx * 0.5 + 0.5;
  78453. var px = Math.round(dx * inputWidth);
  78454. if (px < 0)
  78455. px = 0;
  78456. else if (px >= inputWidth)
  78457. px = inputWidth - 1;
  78458. var py = Math.round(dy * inputHeight);
  78459. if (py < 0)
  78460. py = 0;
  78461. else if (py >= inputHeight)
  78462. py = inputHeight - 1;
  78463. var inputY = (inputHeight - py - 1);
  78464. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  78465. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  78466. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  78467. return {
  78468. r: r,
  78469. g: g,
  78470. b: b
  78471. };
  78472. };
  78473. PanoramaToCubeMapTools.FACE_FRONT = [
  78474. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78475. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78476. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78477. new BABYLON.Vector3(1.0, 1.0, -1.0)
  78478. ];
  78479. PanoramaToCubeMapTools.FACE_BACK = [
  78480. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78481. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78482. new BABYLON.Vector3(1.0, 1.0, 1.0),
  78483. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  78484. ];
  78485. PanoramaToCubeMapTools.FACE_RIGHT = [
  78486. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78487. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78488. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78489. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78490. ];
  78491. PanoramaToCubeMapTools.FACE_LEFT = [
  78492. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78493. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78494. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78495. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  78496. ];
  78497. PanoramaToCubeMapTools.FACE_DOWN = [
  78498. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78499. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78500. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78501. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78502. ];
  78503. PanoramaToCubeMapTools.FACE_UP = [
  78504. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78505. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78506. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78507. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78508. ];
  78509. return PanoramaToCubeMapTools;
  78510. }());
  78511. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78512. })(BABYLON || (BABYLON = {}));
  78513. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78514. var BABYLON;
  78515. (function (BABYLON) {
  78516. ;
  78517. /**
  78518. * This groups tools to convert HDR texture to native colors array.
  78519. */
  78520. var HDRTools = /** @class */ (function () {
  78521. function HDRTools() {
  78522. }
  78523. HDRTools.Ldexp = function (mantissa, exponent) {
  78524. if (exponent > 1023) {
  78525. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78526. }
  78527. if (exponent < -1074) {
  78528. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78529. }
  78530. return mantissa * Math.pow(2, exponent);
  78531. };
  78532. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78533. if (exponent > 0) { /*nonzero pixel*/
  78534. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78535. float32array[index + 0] = red * exponent;
  78536. float32array[index + 1] = green * exponent;
  78537. float32array[index + 2] = blue * exponent;
  78538. }
  78539. else {
  78540. float32array[index + 0] = 0;
  78541. float32array[index + 1] = 0;
  78542. float32array[index + 2] = 0;
  78543. }
  78544. };
  78545. HDRTools.readStringLine = function (uint8array, startIndex) {
  78546. var line = "";
  78547. var character = "";
  78548. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78549. character = String.fromCharCode(uint8array[i]);
  78550. if (character == "\n") {
  78551. break;
  78552. }
  78553. line += character;
  78554. }
  78555. return line;
  78556. };
  78557. /**
  78558. * Reads header information from an RGBE texture stored in a native array.
  78559. * More information on this format are available here:
  78560. * https://en.wikipedia.org/wiki/RGBE_image_format
  78561. *
  78562. * @param uint8array The binary file stored in native array.
  78563. * @return The header information.
  78564. */
  78565. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78566. var height = 0;
  78567. var width = 0;
  78568. var line = this.readStringLine(uint8array, 0);
  78569. if (line[0] != '#' || line[1] != '?') {
  78570. throw "Bad HDR Format.";
  78571. }
  78572. var endOfHeader = false;
  78573. var findFormat = false;
  78574. var lineIndex = 0;
  78575. do {
  78576. lineIndex += (line.length + 1);
  78577. line = this.readStringLine(uint8array, lineIndex);
  78578. if (line == "FORMAT=32-bit_rle_rgbe") {
  78579. findFormat = true;
  78580. }
  78581. else if (line.length == 0) {
  78582. endOfHeader = true;
  78583. }
  78584. } while (!endOfHeader);
  78585. if (!findFormat) {
  78586. throw "HDR Bad header format, unsupported FORMAT";
  78587. }
  78588. lineIndex += (line.length + 1);
  78589. line = this.readStringLine(uint8array, lineIndex);
  78590. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78591. var match = sizeRegexp.exec(line);
  78592. // TODO. Support +Y and -X if needed.
  78593. if (!match || match.length < 3) {
  78594. throw "HDR Bad header format, no size";
  78595. }
  78596. width = parseInt(match[2]);
  78597. height = parseInt(match[1]);
  78598. if (width < 8 || width > 0x7fff) {
  78599. throw "HDR Bad header format, unsupported size";
  78600. }
  78601. lineIndex += (line.length + 1);
  78602. return {
  78603. height: height,
  78604. width: width,
  78605. dataPosition: lineIndex
  78606. };
  78607. };
  78608. /**
  78609. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78610. * This RGBE texture needs to store the information as a panorama.
  78611. *
  78612. * More information on this format are available here:
  78613. * https://en.wikipedia.org/wiki/RGBE_image_format
  78614. *
  78615. * @param buffer The binary file stored in an array buffer.
  78616. * @param size The expected size of the extracted cubemap.
  78617. * @return The Cube Map information.
  78618. */
  78619. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78620. var uint8array = new Uint8Array(buffer);
  78621. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78622. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78623. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78624. return cubeMapData;
  78625. };
  78626. /**
  78627. * Returns the pixels data extracted from an RGBE texture.
  78628. * This pixels will be stored left to right up to down in the R G B order in one array.
  78629. *
  78630. * More information on this format are available here:
  78631. * https://en.wikipedia.org/wiki/RGBE_image_format
  78632. *
  78633. * @param uint8array The binary file stored in an array buffer.
  78634. * @param hdrInfo The header information of the file.
  78635. * @return The pixels data in RGB right to left up to down order.
  78636. */
  78637. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78638. // Keep for multi format supports.
  78639. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78640. };
  78641. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78642. var num_scanlines = hdrInfo.height;
  78643. var scanline_width = hdrInfo.width;
  78644. var a, b, c, d, count;
  78645. var dataIndex = hdrInfo.dataPosition;
  78646. var index = 0, endIndex = 0, i = 0;
  78647. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78648. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78649. // 3 channels of 4 bytes per pixel in float.
  78650. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78651. var resultArray = new Float32Array(resultBuffer);
  78652. // read in each successive scanline
  78653. while (num_scanlines > 0) {
  78654. a = uint8array[dataIndex++];
  78655. b = uint8array[dataIndex++];
  78656. c = uint8array[dataIndex++];
  78657. d = uint8array[dataIndex++];
  78658. if (a != 2 || b != 2 || (c & 0x80)) {
  78659. // this file is not run length encoded
  78660. throw "HDR Bad header format, not RLE";
  78661. }
  78662. if (((c << 8) | d) != scanline_width) {
  78663. throw "HDR Bad header format, wrong scan line width";
  78664. }
  78665. index = 0;
  78666. // read each of the four channels for the scanline into the buffer
  78667. for (i = 0; i < 4; i++) {
  78668. endIndex = (i + 1) * scanline_width;
  78669. while (index < endIndex) {
  78670. a = uint8array[dataIndex++];
  78671. b = uint8array[dataIndex++];
  78672. if (a > 128) {
  78673. // a run of the same value
  78674. count = a - 128;
  78675. if ((count == 0) || (count > endIndex - index)) {
  78676. throw "HDR Bad Format, bad scanline data (run)";
  78677. }
  78678. while (count-- > 0) {
  78679. scanLineArray[index++] = b;
  78680. }
  78681. }
  78682. else {
  78683. // a non-run
  78684. count = a;
  78685. if ((count == 0) || (count > endIndex - index)) {
  78686. throw "HDR Bad Format, bad scanline data (non-run)";
  78687. }
  78688. scanLineArray[index++] = b;
  78689. if (--count > 0) {
  78690. for (var j = 0; j < count; j++) {
  78691. scanLineArray[index++] = uint8array[dataIndex++];
  78692. }
  78693. }
  78694. }
  78695. }
  78696. }
  78697. // now convert data from buffer into floats
  78698. for (i = 0; i < scanline_width; i++) {
  78699. a = scanLineArray[i];
  78700. b = scanLineArray[i + scanline_width];
  78701. c = scanLineArray[i + 2 * scanline_width];
  78702. d = scanLineArray[i + 3 * scanline_width];
  78703. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78704. }
  78705. num_scanlines--;
  78706. }
  78707. return resultArray;
  78708. };
  78709. return HDRTools;
  78710. }());
  78711. BABYLON.HDRTools = HDRTools;
  78712. })(BABYLON || (BABYLON = {}));
  78713. //# sourceMappingURL=babylon.hdr.js.map
  78714. var BABYLON;
  78715. (function (BABYLON) {
  78716. /**
  78717. * This represents a texture coming from an HDR input.
  78718. *
  78719. * The only supported format is currently panorama picture stored in RGBE format.
  78720. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78721. */
  78722. var HDRCubeTexture = /** @class */ (function (_super) {
  78723. __extends(HDRCubeTexture, _super);
  78724. /**
  78725. * Instantiates an HDRTexture from the following parameters.
  78726. *
  78727. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78728. * @param scene The scene the texture will be used in
  78729. * @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.
  78730. * @param noMipmap Forces to not generate the mipmap if true
  78731. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78732. * @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)
  78733. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78734. */
  78735. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78736. if (noMipmap === void 0) { noMipmap = false; }
  78737. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78738. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78739. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78740. if (onLoad === void 0) { onLoad = null; }
  78741. if (onError === void 0) { onError = null; }
  78742. var _this = _super.call(this, scene) || this;
  78743. _this._useInGammaSpace = false;
  78744. _this._generateHarmonics = true;
  78745. _this._isBABYLONPreprocessed = false;
  78746. _this._onLoad = null;
  78747. _this._onError = null;
  78748. /**
  78749. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78750. */
  78751. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78752. /**
  78753. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78754. * This is usefull at run time to apply the good shader.
  78755. */
  78756. _this.isPMREM = false;
  78757. _this._isBlocking = true;
  78758. _this._rotationY = 0;
  78759. /**
  78760. * Gets or sets the center of the bounding box associated with the cube texture
  78761. * It must define where the camera used to render the texture was set
  78762. */
  78763. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78764. if (!url) {
  78765. return _this;
  78766. }
  78767. _this.name = url;
  78768. _this.url = url;
  78769. _this.hasAlpha = false;
  78770. _this.isCube = true;
  78771. _this._textureMatrix = BABYLON.Matrix.Identity();
  78772. _this._onLoad = onLoad;
  78773. _this._onError = onError;
  78774. _this.gammaSpace = false;
  78775. var caps = scene.getEngine().getCaps();
  78776. if (size) {
  78777. _this._isBABYLONPreprocessed = false;
  78778. _this._noMipmap = noMipmap;
  78779. _this._size = size;
  78780. _this._useInGammaSpace = useInGammaSpace;
  78781. _this._usePMREMGenerator = usePMREMGenerator &&
  78782. caps.textureLOD &&
  78783. caps.textureFloat &&
  78784. !_this._useInGammaSpace;
  78785. }
  78786. else {
  78787. _this._isBABYLONPreprocessed = true;
  78788. _this._noMipmap = false;
  78789. _this._useInGammaSpace = false;
  78790. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78791. !_this._useInGammaSpace;
  78792. }
  78793. _this.isPMREM = _this._usePMREMGenerator;
  78794. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78795. if (!_this._texture) {
  78796. if (!scene.useDelayedTextureLoading) {
  78797. _this.loadTexture();
  78798. }
  78799. else {
  78800. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78801. }
  78802. }
  78803. return _this;
  78804. }
  78805. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78806. /**
  78807. * Gets wether or not the texture is blocking during loading.
  78808. */
  78809. get: function () {
  78810. return this._isBlocking;
  78811. },
  78812. /**
  78813. * Sets wether or not the texture is blocking during loading.
  78814. */
  78815. set: function (value) {
  78816. this._isBlocking = value;
  78817. },
  78818. enumerable: true,
  78819. configurable: true
  78820. });
  78821. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78822. /**
  78823. * Gets texture matrix rotation angle around Y axis radians.
  78824. */
  78825. get: function () {
  78826. return this._rotationY;
  78827. },
  78828. /**
  78829. * Sets texture matrix rotation angle around Y axis in radians.
  78830. */
  78831. set: function (value) {
  78832. this._rotationY = value;
  78833. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78834. },
  78835. enumerable: true,
  78836. configurable: true
  78837. });
  78838. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78839. get: function () {
  78840. return this._boundingBoxSize;
  78841. },
  78842. /**
  78843. * Gets or sets the size of the bounding box associated with the cube texture
  78844. * When defined, the cubemap will switch to local mode
  78845. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78846. * @example https://www.babylonjs-playground.com/#RNASML
  78847. */
  78848. set: function (value) {
  78849. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78850. return;
  78851. }
  78852. this._boundingBoxSize = value;
  78853. var scene = this.getScene();
  78854. if (scene) {
  78855. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78856. }
  78857. },
  78858. enumerable: true,
  78859. configurable: true
  78860. });
  78861. /**
  78862. * Occurs when the file is a preprocessed .babylon.hdr file.
  78863. */
  78864. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78865. var _this = this;
  78866. var mipLevels = 0;
  78867. var floatArrayView = null;
  78868. var scene = this.getScene();
  78869. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78870. var mips = new Array();
  78871. if (!floatArrayView) {
  78872. return mips;
  78873. }
  78874. var startIndex = 30;
  78875. for (var level = 0; level < mipLevels; level++) {
  78876. mips.push([]);
  78877. // Fill each pixel of the mip level.
  78878. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78879. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78880. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78881. mips[level].push(faceData);
  78882. startIndex += faceSize;
  78883. }
  78884. }
  78885. return mips;
  78886. } : null;
  78887. var callback = function (buffer) {
  78888. var scene = _this.getScene();
  78889. if (!scene) {
  78890. return null;
  78891. }
  78892. // Create Native Array Views
  78893. var intArrayView = new Int32Array(buffer);
  78894. floatArrayView = new Float32Array(buffer);
  78895. // Fill header.
  78896. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78897. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78898. // Update Texture Information.
  78899. if (!_this._texture) {
  78900. return null;
  78901. }
  78902. _this._texture.updateSize(_this._size, _this._size);
  78903. // Fill polynomial information.
  78904. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78905. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78906. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78907. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78908. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78909. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78910. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78911. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78912. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78913. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78914. _this.sphericalPolynomial = sphericalPolynomial;
  78915. // Fill pixel data.
  78916. mipLevels = intArrayView[29]; // Number of mip levels.
  78917. var startIndex = 30;
  78918. var data = [];
  78919. var faceSize = Math.pow(_this._size, 2) * 3;
  78920. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78921. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  78922. startIndex += faceSize;
  78923. }
  78924. var results = [];
  78925. var byteArray = null;
  78926. // Push each faces.
  78927. for (var k = 0; k < 6; k++) {
  78928. var dataFace = null;
  78929. // To be deprecated.
  78930. if (version === 1) {
  78931. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78932. dataFace = data[j];
  78933. }
  78934. // If special cases.
  78935. if (!mipmapGenerator && dataFace) {
  78936. if (!scene.getEngine().getCaps().textureFloat) {
  78937. // 3 channels of 1 bytes per pixel in bytes.
  78938. var byteBuffer = new ArrayBuffer(faceSize);
  78939. byteArray = new Uint8Array(byteBuffer);
  78940. }
  78941. for (var i = 0; i < _this._size * _this._size; i++) {
  78942. // Put in gamma space if requested.
  78943. if (_this._useInGammaSpace) {
  78944. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78945. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78946. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78947. }
  78948. // Convert to int texture for fallback.
  78949. if (byteArray) {
  78950. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78951. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78952. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78953. // May use luminance instead if the result is not accurate.
  78954. var max = Math.max(Math.max(r, g), b);
  78955. if (max > 255) {
  78956. var scale = 255 / max;
  78957. r *= scale;
  78958. g *= scale;
  78959. b *= scale;
  78960. }
  78961. byteArray[(i * 3) + 0] = r;
  78962. byteArray[(i * 3) + 1] = g;
  78963. byteArray[(i * 3) + 2] = b;
  78964. }
  78965. }
  78966. }
  78967. // Fill the array accordingly.
  78968. if (byteArray) {
  78969. results.push(byteArray);
  78970. }
  78971. else {
  78972. results.push(dataFace);
  78973. }
  78974. }
  78975. return results;
  78976. };
  78977. if (scene) {
  78978. 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);
  78979. }
  78980. };
  78981. /**
  78982. * Occurs when the file is raw .hdr file.
  78983. */
  78984. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78985. var _this = this;
  78986. var callback = function (buffer) {
  78987. var scene = _this.getScene();
  78988. if (!scene) {
  78989. return null;
  78990. }
  78991. // Extract the raw linear data.
  78992. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78993. // Generate harmonics if needed.
  78994. if (_this._generateHarmonics) {
  78995. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78996. _this.sphericalPolynomial = sphericalPolynomial;
  78997. }
  78998. var results = [];
  78999. var byteArray = null;
  79000. // Push each faces.
  79001. for (var j = 0; j < 6; j++) {
  79002. // Create uintarray fallback.
  79003. if (!scene.getEngine().getCaps().textureFloat) {
  79004. // 3 channels of 1 bytes per pixel in bytes.
  79005. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79006. byteArray = new Uint8Array(byteBuffer);
  79007. }
  79008. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79009. // If special cases.
  79010. if (_this._useInGammaSpace || byteArray) {
  79011. for (var i = 0; i < _this._size * _this._size; i++) {
  79012. // Put in gamma space if requested.
  79013. if (_this._useInGammaSpace) {
  79014. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79015. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79016. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79017. }
  79018. // Convert to int texture for fallback.
  79019. if (byteArray) {
  79020. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79021. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79022. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79023. // May use luminance instead if the result is not accurate.
  79024. var max = Math.max(Math.max(r, g), b);
  79025. if (max > 255) {
  79026. var scale = 255 / max;
  79027. r *= scale;
  79028. g *= scale;
  79029. b *= scale;
  79030. }
  79031. byteArray[(i * 3) + 0] = r;
  79032. byteArray[(i * 3) + 1] = g;
  79033. byteArray[(i * 3) + 2] = b;
  79034. }
  79035. }
  79036. }
  79037. if (byteArray) {
  79038. results.push(byteArray);
  79039. }
  79040. else {
  79041. results.push(dataFace);
  79042. }
  79043. }
  79044. return results;
  79045. };
  79046. var mipmapGenerator = null;
  79047. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79048. // if (!this._noMipmap &&
  79049. // this._usePMREMGenerator) {
  79050. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79051. // // Custom setup of the generator matching with the PBR shader values.
  79052. // var generator = new BABYLON.PMREMGenerator(data,
  79053. // this._size,
  79054. // this._size,
  79055. // 0,
  79056. // 3,
  79057. // this.getScene().getEngine().getCaps().textureFloat,
  79058. // 2048,
  79059. // 0.25,
  79060. // false,
  79061. // true);
  79062. // return generator.filterCubeMap();
  79063. // };
  79064. // }
  79065. var scene = this.getScene();
  79066. if (scene) {
  79067. 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);
  79068. }
  79069. };
  79070. /**
  79071. * Starts the loading process of the texture.
  79072. */
  79073. HDRCubeTexture.prototype.loadTexture = function () {
  79074. if (this._isBABYLONPreprocessed) {
  79075. this.loadBabylonTexture();
  79076. }
  79077. else {
  79078. this.loadHDRTexture();
  79079. }
  79080. };
  79081. HDRCubeTexture.prototype.clone = function () {
  79082. var scene = this.getScene();
  79083. if (!scene) {
  79084. return this;
  79085. }
  79086. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79087. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79088. // Base texture
  79089. newTexture.level = this.level;
  79090. newTexture.wrapU = this.wrapU;
  79091. newTexture.wrapV = this.wrapV;
  79092. newTexture.coordinatesIndex = this.coordinatesIndex;
  79093. newTexture.coordinatesMode = this.coordinatesMode;
  79094. return newTexture;
  79095. };
  79096. // Methods
  79097. HDRCubeTexture.prototype.delayLoad = function () {
  79098. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79099. return;
  79100. }
  79101. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79102. this._texture = this._getFromCache(this.url, this._noMipmap);
  79103. if (!this._texture) {
  79104. this.loadTexture();
  79105. }
  79106. };
  79107. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79108. return this._textureMatrix;
  79109. };
  79110. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79111. this._textureMatrix = value;
  79112. };
  79113. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79114. var texture = null;
  79115. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79116. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79117. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79118. texture.name = parsedTexture.name;
  79119. texture.hasAlpha = parsedTexture.hasAlpha;
  79120. texture.level = parsedTexture.level;
  79121. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79122. texture.isBlocking = parsedTexture.isBlocking;
  79123. }
  79124. if (texture) {
  79125. if (parsedTexture.boundingBoxPosition) {
  79126. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79127. }
  79128. if (parsedTexture.boundingBoxSize) {
  79129. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79130. }
  79131. if (parsedTexture.rotationY) {
  79132. texture.rotationY = parsedTexture.rotationY;
  79133. }
  79134. }
  79135. return texture;
  79136. };
  79137. HDRCubeTexture.prototype.serialize = function () {
  79138. if (!this.name) {
  79139. return null;
  79140. }
  79141. var serializationObject = {};
  79142. serializationObject.name = this.name;
  79143. serializationObject.hasAlpha = this.hasAlpha;
  79144. serializationObject.isCube = true;
  79145. serializationObject.level = this.level;
  79146. serializationObject.size = this._size;
  79147. serializationObject.coordinatesMode = this.coordinatesMode;
  79148. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79149. serializationObject.generateHarmonics = this._generateHarmonics;
  79150. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79151. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79152. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79153. serializationObject.noMipmap = this._noMipmap;
  79154. serializationObject.isBlocking = this._isBlocking;
  79155. serializationObject.rotationY = this._rotationY;
  79156. return serializationObject;
  79157. };
  79158. /**
  79159. * Saves as a file the data contained in the texture in a binary format.
  79160. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79161. * as the spherical used in the lighting.
  79162. * @param url The HDR file url.
  79163. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79164. * @param onError Method called if any error happens during download.
  79165. * @return The packed binary data.
  79166. */
  79167. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79168. if (onError === void 0) { onError = null; }
  79169. var callback = function (buffer) {
  79170. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79171. // Returns a URL you can use as a href.
  79172. var objUrl = window.URL.createObjectURL(data);
  79173. // Simulates a link to it and click to dowload.
  79174. var a = document.createElement("a");
  79175. document.body.appendChild(a);
  79176. a.style.display = "none";
  79177. a.href = objUrl;
  79178. a.download = "envmap.babylon.hdr";
  79179. a.click();
  79180. };
  79181. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79182. };
  79183. /**
  79184. * Serializes the data contained in the texture in a binary format.
  79185. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79186. * as the spherical used in the lighting.
  79187. * @param url The HDR file url.
  79188. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79189. * @param onError Method called if any error happens during download.
  79190. * @return The packed binary data.
  79191. */
  79192. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79193. if (onError === void 0) { onError = null; }
  79194. // Needs the url tho create the texture.
  79195. if (!url) {
  79196. return;
  79197. }
  79198. // Check Power of two size.
  79199. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  79200. return;
  79201. }
  79202. // Coming Back in 3.x.
  79203. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79204. };
  79205. HDRCubeTexture._facesMapping = [
  79206. "right",
  79207. "left",
  79208. "up",
  79209. "down",
  79210. "front",
  79211. "back"
  79212. ];
  79213. return HDRCubeTexture;
  79214. }(BABYLON.BaseTexture));
  79215. BABYLON.HDRCubeTexture = HDRCubeTexture;
  79216. })(BABYLON || (BABYLON = {}));
  79217. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  79218. var BABYLON;
  79219. (function (BABYLON) {
  79220. var IndexedVector2 = /** @class */ (function (_super) {
  79221. __extends(IndexedVector2, _super);
  79222. function IndexedVector2(original, index) {
  79223. var _this = _super.call(this, original.x, original.y) || this;
  79224. _this.index = index;
  79225. return _this;
  79226. }
  79227. return IndexedVector2;
  79228. }(BABYLON.Vector2));
  79229. var PolygonPoints = /** @class */ (function () {
  79230. function PolygonPoints() {
  79231. this.elements = new Array();
  79232. }
  79233. PolygonPoints.prototype.add = function (originalPoints) {
  79234. var _this = this;
  79235. var result = new Array();
  79236. originalPoints.forEach(function (point) {
  79237. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79238. var newPoint = new IndexedVector2(point, _this.elements.length);
  79239. result.push(newPoint);
  79240. _this.elements.push(newPoint);
  79241. }
  79242. });
  79243. return result;
  79244. };
  79245. PolygonPoints.prototype.computeBounds = function () {
  79246. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79247. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79248. this.elements.forEach(function (point) {
  79249. // x
  79250. if (point.x < lmin.x) {
  79251. lmin.x = point.x;
  79252. }
  79253. else if (point.x > lmax.x) {
  79254. lmax.x = point.x;
  79255. }
  79256. // y
  79257. if (point.y < lmin.y) {
  79258. lmin.y = point.y;
  79259. }
  79260. else if (point.y > lmax.y) {
  79261. lmax.y = point.y;
  79262. }
  79263. });
  79264. return {
  79265. min: lmin,
  79266. max: lmax,
  79267. width: lmax.x - lmin.x,
  79268. height: lmax.y - lmin.y
  79269. };
  79270. };
  79271. return PolygonPoints;
  79272. }());
  79273. var Polygon = /** @class */ (function () {
  79274. function Polygon() {
  79275. }
  79276. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79277. return [
  79278. new BABYLON.Vector2(xmin, ymin),
  79279. new BABYLON.Vector2(xmax, ymin),
  79280. new BABYLON.Vector2(xmax, ymax),
  79281. new BABYLON.Vector2(xmin, ymax)
  79282. ];
  79283. };
  79284. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79285. if (cx === void 0) { cx = 0; }
  79286. if (cy === void 0) { cy = 0; }
  79287. if (numberOfSides === void 0) { numberOfSides = 32; }
  79288. var result = new Array();
  79289. var angle = 0;
  79290. var increment = (Math.PI * 2) / numberOfSides;
  79291. for (var i = 0; i < numberOfSides; i++) {
  79292. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79293. angle -= increment;
  79294. }
  79295. return result;
  79296. };
  79297. Polygon.Parse = function (input) {
  79298. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79299. var i, result = [];
  79300. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79301. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79302. }
  79303. return result;
  79304. };
  79305. Polygon.StartingAt = function (x, y) {
  79306. return BABYLON.Path2.StartingAt(x, y);
  79307. };
  79308. return Polygon;
  79309. }());
  79310. BABYLON.Polygon = Polygon;
  79311. var PolygonMeshBuilder = /** @class */ (function () {
  79312. function PolygonMeshBuilder(name, contours, scene) {
  79313. this._points = new PolygonPoints();
  79314. this._outlinepoints = new PolygonPoints();
  79315. this._holes = new Array();
  79316. this._epoints = new Array();
  79317. this._eholes = new Array();
  79318. this._name = name;
  79319. this._scene = scene;
  79320. var points;
  79321. if (contours instanceof BABYLON.Path2) {
  79322. points = contours.getPoints();
  79323. }
  79324. else {
  79325. points = contours;
  79326. }
  79327. this._addToepoint(points);
  79328. this._points.add(points);
  79329. this._outlinepoints.add(points);
  79330. if (typeof earcut === 'undefined') {
  79331. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  79332. }
  79333. }
  79334. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  79335. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  79336. var p = points_1[_i];
  79337. this._epoints.push(p.x, p.y);
  79338. }
  79339. };
  79340. PolygonMeshBuilder.prototype.addHole = function (hole) {
  79341. this._points.add(hole);
  79342. var holepoints = new PolygonPoints();
  79343. holepoints.add(hole);
  79344. this._holes.push(holepoints);
  79345. this._eholes.push(this._epoints.length / 2);
  79346. this._addToepoint(hole);
  79347. return this;
  79348. };
  79349. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  79350. var _this = this;
  79351. if (updatable === void 0) { updatable = false; }
  79352. if (depth === void 0) { depth = 0; }
  79353. var result = new BABYLON.Mesh(this._name, this._scene);
  79354. var normals = new Array();
  79355. var positions = new Array();
  79356. var uvs = new Array();
  79357. var bounds = this._points.computeBounds();
  79358. this._points.elements.forEach(function (p) {
  79359. normals.push(0, 1.0, 0);
  79360. positions.push(p.x, 0, p.y);
  79361. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  79362. });
  79363. var indices = new Array();
  79364. var res = earcut(this._epoints, this._eholes, 2);
  79365. for (var i = 0; i < res.length; i++) {
  79366. indices.push(res[i]);
  79367. }
  79368. if (depth > 0) {
  79369. var positionscount = (positions.length / 3); //get the current pointcount
  79370. this._points.elements.forEach(function (p) {
  79371. normals.push(0, -1.0, 0);
  79372. positions.push(p.x, -depth, p.y);
  79373. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  79374. });
  79375. var totalCount = indices.length;
  79376. for (var i = 0; i < totalCount; i += 3) {
  79377. var i0 = indices[i + 0];
  79378. var i1 = indices[i + 1];
  79379. var i2 = indices[i + 2];
  79380. indices.push(i2 + positionscount);
  79381. indices.push(i1 + positionscount);
  79382. indices.push(i0 + positionscount);
  79383. }
  79384. //Add the sides
  79385. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  79386. this._holes.forEach(function (hole) {
  79387. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  79388. });
  79389. }
  79390. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  79391. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  79392. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  79393. result.setIndices(indices);
  79394. return result;
  79395. };
  79396. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  79397. var StartIndex = positions.length / 3;
  79398. var ulength = 0;
  79399. for (var i = 0; i < points.elements.length; i++) {
  79400. var p = points.elements[i];
  79401. var p1;
  79402. if ((i + 1) > points.elements.length - 1) {
  79403. p1 = points.elements[0];
  79404. }
  79405. else {
  79406. p1 = points.elements[i + 1];
  79407. }
  79408. positions.push(p.x, 0, p.y);
  79409. positions.push(p.x, -depth, p.y);
  79410. positions.push(p1.x, 0, p1.y);
  79411. positions.push(p1.x, -depth, p1.y);
  79412. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  79413. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  79414. var v3 = v2.subtract(v1);
  79415. var v4 = new BABYLON.Vector3(0, 1, 0);
  79416. var vn = BABYLON.Vector3.Cross(v3, v4);
  79417. vn = vn.normalize();
  79418. uvs.push(ulength / bounds.width, 0);
  79419. uvs.push(ulength / bounds.width, 1);
  79420. ulength += v3.length();
  79421. uvs.push((ulength / bounds.width), 0);
  79422. uvs.push((ulength / bounds.width), 1);
  79423. if (!flip) {
  79424. normals.push(-vn.x, -vn.y, -vn.z);
  79425. normals.push(-vn.x, -vn.y, -vn.z);
  79426. normals.push(-vn.x, -vn.y, -vn.z);
  79427. normals.push(-vn.x, -vn.y, -vn.z);
  79428. indices.push(StartIndex);
  79429. indices.push(StartIndex + 1);
  79430. indices.push(StartIndex + 2);
  79431. indices.push(StartIndex + 1);
  79432. indices.push(StartIndex + 3);
  79433. indices.push(StartIndex + 2);
  79434. }
  79435. else {
  79436. normals.push(vn.x, vn.y, vn.z);
  79437. normals.push(vn.x, vn.y, vn.z);
  79438. normals.push(vn.x, vn.y, vn.z);
  79439. normals.push(vn.x, vn.y, vn.z);
  79440. indices.push(StartIndex);
  79441. indices.push(StartIndex + 2);
  79442. indices.push(StartIndex + 1);
  79443. indices.push(StartIndex + 1);
  79444. indices.push(StartIndex + 2);
  79445. indices.push(StartIndex + 3);
  79446. }
  79447. StartIndex += 4;
  79448. }
  79449. ;
  79450. };
  79451. return PolygonMeshBuilder;
  79452. }());
  79453. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  79454. })(BABYLON || (BABYLON = {}));
  79455. //# sourceMappingURL=babylon.polygonMesh.js.map
  79456. var BABYLON;
  79457. (function (BABYLON) {
  79458. // Unique ID when we import meshes from Babylon to CSG
  79459. var currentCSGMeshId = 0;
  79460. // # class Vertex
  79461. // Represents a vertex of a polygon. Use your own vertex class instead of this
  79462. // one to provide additional features like texture coordinates and vertex
  79463. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  79464. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  79465. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  79466. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  79467. // is not used anywhere else.
  79468. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  79469. var Vertex = /** @class */ (function () {
  79470. function Vertex(pos, normal, uv) {
  79471. this.pos = pos;
  79472. this.normal = normal;
  79473. this.uv = uv;
  79474. }
  79475. Vertex.prototype.clone = function () {
  79476. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  79477. };
  79478. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  79479. // orientation of a polygon is flipped.
  79480. Vertex.prototype.flip = function () {
  79481. this.normal = this.normal.scale(-1);
  79482. };
  79483. // Create a new vertex between this vertex and `other` by linearly
  79484. // interpolating all properties using a parameter of `t`. Subclasses should
  79485. // override this to interpolate additional properties.
  79486. Vertex.prototype.interpolate = function (other, t) {
  79487. 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));
  79488. };
  79489. return Vertex;
  79490. }());
  79491. // # class Plane
  79492. // Represents a plane in 3D space.
  79493. var Plane = /** @class */ (function () {
  79494. function Plane(normal, w) {
  79495. this.normal = normal;
  79496. this.w = w;
  79497. }
  79498. Plane.FromPoints = function (a, b, c) {
  79499. var v0 = c.subtract(a);
  79500. var v1 = b.subtract(a);
  79501. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79502. return null;
  79503. }
  79504. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79505. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79506. };
  79507. Plane.prototype.clone = function () {
  79508. return new Plane(this.normal.clone(), this.w);
  79509. };
  79510. Plane.prototype.flip = function () {
  79511. this.normal.scaleInPlace(-1);
  79512. this.w = -this.w;
  79513. };
  79514. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79515. // fragments in the appropriate lists. Coplanar polygons go into either
  79516. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79517. // respect to this plane. Polygons in front or in back of this plane go into
  79518. // either `front` or `back`.
  79519. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79520. var COPLANAR = 0;
  79521. var FRONT = 1;
  79522. var BACK = 2;
  79523. var SPANNING = 3;
  79524. // Classify each point as well as the entire polygon into one of the above
  79525. // four classes.
  79526. var polygonType = 0;
  79527. var types = [];
  79528. var i;
  79529. var t;
  79530. for (i = 0; i < polygon.vertices.length; i++) {
  79531. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79532. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79533. polygonType |= type;
  79534. types.push(type);
  79535. }
  79536. // Put the polygon in the correct list, splitting it when necessary.
  79537. switch (polygonType) {
  79538. case COPLANAR:
  79539. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79540. break;
  79541. case FRONT:
  79542. front.push(polygon);
  79543. break;
  79544. case BACK:
  79545. back.push(polygon);
  79546. break;
  79547. case SPANNING:
  79548. var f = [], b = [];
  79549. for (i = 0; i < polygon.vertices.length; i++) {
  79550. var j = (i + 1) % polygon.vertices.length;
  79551. var ti = types[i], tj = types[j];
  79552. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79553. if (ti !== BACK)
  79554. f.push(vi);
  79555. if (ti !== FRONT)
  79556. b.push(ti !== BACK ? vi.clone() : vi);
  79557. if ((ti | tj) === SPANNING) {
  79558. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79559. var v = vi.interpolate(vj, t);
  79560. f.push(v);
  79561. b.push(v.clone());
  79562. }
  79563. }
  79564. var poly;
  79565. if (f.length >= 3) {
  79566. poly = new Polygon(f, polygon.shared);
  79567. if (poly.plane)
  79568. front.push(poly);
  79569. }
  79570. if (b.length >= 3) {
  79571. poly = new Polygon(b, polygon.shared);
  79572. if (poly.plane)
  79573. back.push(poly);
  79574. }
  79575. break;
  79576. }
  79577. };
  79578. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79579. // point is on the plane.
  79580. Plane.EPSILON = 1e-5;
  79581. return Plane;
  79582. }());
  79583. // # class Polygon
  79584. // Represents a convex polygon. The vertices used to initialize a polygon must
  79585. // be coplanar and form a convex loop.
  79586. //
  79587. // Each convex polygon has a `shared` property, which is shared between all
  79588. // polygons that are clones of each other or were split from the same polygon.
  79589. // This can be used to define per-polygon properties (such as surface color).
  79590. var Polygon = /** @class */ (function () {
  79591. function Polygon(vertices, shared) {
  79592. this.vertices = vertices;
  79593. this.shared = shared;
  79594. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79595. }
  79596. Polygon.prototype.clone = function () {
  79597. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79598. return new Polygon(vertices, this.shared);
  79599. };
  79600. Polygon.prototype.flip = function () {
  79601. this.vertices.reverse().map(function (v) { v.flip(); });
  79602. this.plane.flip();
  79603. };
  79604. return Polygon;
  79605. }());
  79606. // # class Node
  79607. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79608. // by picking a polygon to split along. That polygon (and all other coplanar
  79609. // polygons) are added directly to that node and the other polygons are added to
  79610. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79611. // no distinction between internal and leaf nodes.
  79612. var Node = /** @class */ (function () {
  79613. function Node(polygons) {
  79614. this.plane = null;
  79615. this.front = null;
  79616. this.back = null;
  79617. this.polygons = new Array();
  79618. if (polygons) {
  79619. this.build(polygons);
  79620. }
  79621. }
  79622. Node.prototype.clone = function () {
  79623. var node = new Node();
  79624. node.plane = this.plane && this.plane.clone();
  79625. node.front = this.front && this.front.clone();
  79626. node.back = this.back && this.back.clone();
  79627. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79628. return node;
  79629. };
  79630. // Convert solid space to empty space and empty space to solid space.
  79631. Node.prototype.invert = function () {
  79632. for (var i = 0; i < this.polygons.length; i++) {
  79633. this.polygons[i].flip();
  79634. }
  79635. if (this.plane) {
  79636. this.plane.flip();
  79637. }
  79638. if (this.front) {
  79639. this.front.invert();
  79640. }
  79641. if (this.back) {
  79642. this.back.invert();
  79643. }
  79644. var temp = this.front;
  79645. this.front = this.back;
  79646. this.back = temp;
  79647. };
  79648. // Recursively remove all polygons in `polygons` that are inside this BSP
  79649. // tree.
  79650. Node.prototype.clipPolygons = function (polygons) {
  79651. if (!this.plane)
  79652. return polygons.slice();
  79653. var front = new Array(), back = new Array();
  79654. for (var i = 0; i < polygons.length; i++) {
  79655. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79656. }
  79657. if (this.front) {
  79658. front = this.front.clipPolygons(front);
  79659. }
  79660. if (this.back) {
  79661. back = this.back.clipPolygons(back);
  79662. }
  79663. else {
  79664. back = [];
  79665. }
  79666. return front.concat(back);
  79667. };
  79668. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79669. // `bsp`.
  79670. Node.prototype.clipTo = function (bsp) {
  79671. this.polygons = bsp.clipPolygons(this.polygons);
  79672. if (this.front)
  79673. this.front.clipTo(bsp);
  79674. if (this.back)
  79675. this.back.clipTo(bsp);
  79676. };
  79677. // Return a list of all polygons in this BSP tree.
  79678. Node.prototype.allPolygons = function () {
  79679. var polygons = this.polygons.slice();
  79680. if (this.front)
  79681. polygons = polygons.concat(this.front.allPolygons());
  79682. if (this.back)
  79683. polygons = polygons.concat(this.back.allPolygons());
  79684. return polygons;
  79685. };
  79686. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79687. // new polygons are filtered down to the bottom of the tree and become new
  79688. // nodes there. Each set of polygons is partitioned using the first polygon
  79689. // (no heuristic is used to pick a good split).
  79690. Node.prototype.build = function (polygons) {
  79691. if (!polygons.length)
  79692. return;
  79693. if (!this.plane)
  79694. this.plane = polygons[0].plane.clone();
  79695. var front = new Array(), back = new Array();
  79696. for (var i = 0; i < polygons.length; i++) {
  79697. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79698. }
  79699. if (front.length) {
  79700. if (!this.front)
  79701. this.front = new Node();
  79702. this.front.build(front);
  79703. }
  79704. if (back.length) {
  79705. if (!this.back)
  79706. this.back = new Node();
  79707. this.back.build(back);
  79708. }
  79709. };
  79710. return Node;
  79711. }());
  79712. var CSG = /** @class */ (function () {
  79713. function CSG() {
  79714. this.polygons = new Array();
  79715. }
  79716. // Convert BABYLON.Mesh to BABYLON.CSG
  79717. CSG.FromMesh = function (mesh) {
  79718. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79719. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79720. if (mesh instanceof BABYLON.Mesh) {
  79721. mesh.computeWorldMatrix(true);
  79722. matrix = mesh.getWorldMatrix();
  79723. meshPosition = mesh.position.clone();
  79724. meshRotation = mesh.rotation.clone();
  79725. if (mesh.rotationQuaternion) {
  79726. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79727. }
  79728. meshScaling = mesh.scaling.clone();
  79729. }
  79730. else {
  79731. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79732. }
  79733. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79734. var subMeshes = mesh.subMeshes;
  79735. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79736. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79737. vertices = [];
  79738. for (var j = 0; j < 3; j++) {
  79739. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79740. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79741. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79742. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79743. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79744. vertex = new Vertex(position, normal, uv);
  79745. vertices.push(vertex);
  79746. }
  79747. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79748. // To handle the case of degenerated triangle
  79749. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79750. if (polygon.plane)
  79751. polygons.push(polygon);
  79752. }
  79753. }
  79754. var csg = CSG.FromPolygons(polygons);
  79755. csg.matrix = matrix;
  79756. csg.position = meshPosition;
  79757. csg.rotation = meshRotation;
  79758. csg.scaling = meshScaling;
  79759. csg.rotationQuaternion = meshRotationQuaternion;
  79760. currentCSGMeshId++;
  79761. return csg;
  79762. };
  79763. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79764. CSG.FromPolygons = function (polygons) {
  79765. var csg = new CSG();
  79766. csg.polygons = polygons;
  79767. return csg;
  79768. };
  79769. CSG.prototype.clone = function () {
  79770. var csg = new CSG();
  79771. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79772. csg.copyTransformAttributes(this);
  79773. return csg;
  79774. };
  79775. CSG.prototype.union = function (csg) {
  79776. var a = new Node(this.clone().polygons);
  79777. var b = new Node(csg.clone().polygons);
  79778. a.clipTo(b);
  79779. b.clipTo(a);
  79780. b.invert();
  79781. b.clipTo(a);
  79782. b.invert();
  79783. a.build(b.allPolygons());
  79784. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79785. };
  79786. CSG.prototype.unionInPlace = function (csg) {
  79787. var a = new Node(this.polygons);
  79788. var b = new Node(csg.polygons);
  79789. a.clipTo(b);
  79790. b.clipTo(a);
  79791. b.invert();
  79792. b.clipTo(a);
  79793. b.invert();
  79794. a.build(b.allPolygons());
  79795. this.polygons = a.allPolygons();
  79796. };
  79797. CSG.prototype.subtract = function (csg) {
  79798. var a = new Node(this.clone().polygons);
  79799. var b = new Node(csg.clone().polygons);
  79800. a.invert();
  79801. a.clipTo(b);
  79802. b.clipTo(a);
  79803. b.invert();
  79804. b.clipTo(a);
  79805. b.invert();
  79806. a.build(b.allPolygons());
  79807. a.invert();
  79808. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79809. };
  79810. CSG.prototype.subtractInPlace = function (csg) {
  79811. var a = new Node(this.polygons);
  79812. var b = new Node(csg.polygons);
  79813. a.invert();
  79814. a.clipTo(b);
  79815. b.clipTo(a);
  79816. b.invert();
  79817. b.clipTo(a);
  79818. b.invert();
  79819. a.build(b.allPolygons());
  79820. a.invert();
  79821. this.polygons = a.allPolygons();
  79822. };
  79823. CSG.prototype.intersect = function (csg) {
  79824. var a = new Node(this.clone().polygons);
  79825. var b = new Node(csg.clone().polygons);
  79826. a.invert();
  79827. b.clipTo(a);
  79828. b.invert();
  79829. a.clipTo(b);
  79830. b.clipTo(a);
  79831. a.build(b.allPolygons());
  79832. a.invert();
  79833. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79834. };
  79835. CSG.prototype.intersectInPlace = function (csg) {
  79836. var a = new Node(this.polygons);
  79837. var b = new Node(csg.polygons);
  79838. a.invert();
  79839. b.clipTo(a);
  79840. b.invert();
  79841. a.clipTo(b);
  79842. b.clipTo(a);
  79843. a.build(b.allPolygons());
  79844. a.invert();
  79845. this.polygons = a.allPolygons();
  79846. };
  79847. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79848. // not modified.
  79849. CSG.prototype.inverse = function () {
  79850. var csg = this.clone();
  79851. csg.inverseInPlace();
  79852. return csg;
  79853. };
  79854. CSG.prototype.inverseInPlace = function () {
  79855. this.polygons.map(function (p) { p.flip(); });
  79856. };
  79857. // This is used to keep meshes transformations so they can be restored
  79858. // when we build back a Babylon Mesh
  79859. // NB : All CSG operations are performed in world coordinates
  79860. CSG.prototype.copyTransformAttributes = function (csg) {
  79861. this.matrix = csg.matrix;
  79862. this.position = csg.position;
  79863. this.rotation = csg.rotation;
  79864. this.scaling = csg.scaling;
  79865. this.rotationQuaternion = csg.rotationQuaternion;
  79866. return this;
  79867. };
  79868. // Build Raw mesh from CSG
  79869. // Coordinates here are in world space
  79870. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79871. var matrix = this.matrix.clone();
  79872. matrix.invert();
  79873. 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;
  79874. if (keepSubMeshes) {
  79875. // Sort Polygons, since subMeshes are indices range
  79876. polygons.sort(function (a, b) {
  79877. if (a.shared.meshId === b.shared.meshId) {
  79878. return a.shared.subMeshId - b.shared.subMeshId;
  79879. }
  79880. else {
  79881. return a.shared.meshId - b.shared.meshId;
  79882. }
  79883. });
  79884. }
  79885. for (var i = 0, il = polygons.length; i < il; i++) {
  79886. polygon = polygons[i];
  79887. // Building SubMeshes
  79888. if (!subMesh_dict[polygon.shared.meshId]) {
  79889. subMesh_dict[polygon.shared.meshId] = {};
  79890. }
  79891. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79892. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79893. indexStart: +Infinity,
  79894. indexEnd: -Infinity,
  79895. materialIndex: polygon.shared.materialIndex
  79896. };
  79897. }
  79898. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79899. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79900. polygonIndices[0] = 0;
  79901. polygonIndices[1] = j - 1;
  79902. polygonIndices[2] = j;
  79903. for (var k = 0; k < 3; k++) {
  79904. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79905. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79906. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79907. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79908. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79909. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79910. // Check if 2 points can be merged
  79911. if (!(typeof vertex_idx !== 'undefined' &&
  79912. normals[vertex_idx * 3] === localNormal.x &&
  79913. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79914. normals[vertex_idx * 3 + 2] === localNormal.z &&
  79915. uvs[vertex_idx * 2] === uv.x &&
  79916. uvs[vertex_idx * 2 + 1] === uv.y)) {
  79917. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  79918. uvs.push(uv.x, uv.y);
  79919. normals.push(normal.x, normal.y, normal.z);
  79920. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  79921. }
  79922. indices.push(vertex_idx);
  79923. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  79924. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  79925. currentIndex++;
  79926. }
  79927. }
  79928. }
  79929. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79930. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79931. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79932. mesh.setIndices(indices, null);
  79933. if (keepSubMeshes) {
  79934. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79935. var materialIndexOffset = 0, materialMaxIndex;
  79936. mesh.subMeshes = new Array();
  79937. for (var m in subMesh_dict) {
  79938. materialMaxIndex = -1;
  79939. for (var sm in subMesh_dict[m]) {
  79940. subMesh_obj = subMesh_dict[m][sm];
  79941. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79942. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79943. }
  79944. materialIndexOffset += ++materialMaxIndex;
  79945. }
  79946. }
  79947. return mesh;
  79948. };
  79949. // Build Mesh from CSG taking material and transforms into account
  79950. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79951. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79952. mesh.material = material;
  79953. mesh.position.copyFrom(this.position);
  79954. mesh.rotation.copyFrom(this.rotation);
  79955. if (this.rotationQuaternion) {
  79956. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79957. }
  79958. mesh.scaling.copyFrom(this.scaling);
  79959. mesh.computeWorldMatrix(true);
  79960. return mesh;
  79961. };
  79962. return CSG;
  79963. }());
  79964. BABYLON.CSG = CSG;
  79965. })(BABYLON || (BABYLON = {}));
  79966. //# sourceMappingURL=babylon.csg.js.map
  79967. var BABYLON;
  79968. (function (BABYLON) {
  79969. var LensFlare = /** @class */ (function () {
  79970. function LensFlare(size, position, color, imgUrl, system) {
  79971. this.size = size;
  79972. this.position = position;
  79973. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79974. this.color = color || new BABYLON.Color3(1, 1, 1);
  79975. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79976. this._system = system;
  79977. system.lensFlares.push(this);
  79978. }
  79979. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79980. return new LensFlare(size, position, color, imgUrl, system);
  79981. };
  79982. LensFlare.prototype.dispose = function () {
  79983. if (this.texture) {
  79984. this.texture.dispose();
  79985. }
  79986. // Remove from scene
  79987. var index = this._system.lensFlares.indexOf(this);
  79988. this._system.lensFlares.splice(index, 1);
  79989. };
  79990. ;
  79991. return LensFlare;
  79992. }());
  79993. BABYLON.LensFlare = LensFlare;
  79994. })(BABYLON || (BABYLON = {}));
  79995. //# sourceMappingURL=babylon.lensFlare.js.map
  79996. var BABYLON;
  79997. (function (BABYLON) {
  79998. var LensFlareSystem = /** @class */ (function () {
  79999. function LensFlareSystem(name, emitter, scene) {
  80000. this.name = name;
  80001. this.lensFlares = new Array();
  80002. this.borderLimit = 300;
  80003. this.viewportBorder = 0;
  80004. this.layerMask = 0x0FFFFFFF;
  80005. this._vertexBuffers = {};
  80006. this._isEnabled = true;
  80007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80008. this._emitter = emitter;
  80009. this.id = name;
  80010. scene.lensFlareSystems.push(this);
  80011. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80012. var engine = scene.getEngine();
  80013. // VBO
  80014. var vertices = [];
  80015. vertices.push(1, 1);
  80016. vertices.push(-1, 1);
  80017. vertices.push(-1, -1);
  80018. vertices.push(1, -1);
  80019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80020. // Indices
  80021. var indices = [];
  80022. indices.push(0);
  80023. indices.push(1);
  80024. indices.push(2);
  80025. indices.push(0);
  80026. indices.push(2);
  80027. indices.push(3);
  80028. this._indexBuffer = engine.createIndexBuffer(indices);
  80029. // Effects
  80030. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80031. }
  80032. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80033. get: function () {
  80034. return this._isEnabled;
  80035. },
  80036. set: function (value) {
  80037. this._isEnabled = value;
  80038. },
  80039. enumerable: true,
  80040. configurable: true
  80041. });
  80042. LensFlareSystem.prototype.getScene = function () {
  80043. return this._scene;
  80044. };
  80045. LensFlareSystem.prototype.getEmitter = function () {
  80046. return this._emitter;
  80047. };
  80048. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80049. this._emitter = newEmitter;
  80050. };
  80051. LensFlareSystem.prototype.getEmitterPosition = function () {
  80052. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80053. };
  80054. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80055. var position = this.getEmitterPosition();
  80056. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80057. this._positionX = position.x;
  80058. this._positionY = position.y;
  80059. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80060. if (this.viewportBorder > 0) {
  80061. globalViewport.x -= this.viewportBorder;
  80062. globalViewport.y -= this.viewportBorder;
  80063. globalViewport.width += this.viewportBorder * 2;
  80064. globalViewport.height += this.viewportBorder * 2;
  80065. position.x += this.viewportBorder;
  80066. position.y += this.viewportBorder;
  80067. this._positionX += this.viewportBorder;
  80068. this._positionY += this.viewportBorder;
  80069. }
  80070. if (position.z > 0) {
  80071. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80072. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80073. return true;
  80074. }
  80075. return true;
  80076. }
  80077. return false;
  80078. };
  80079. LensFlareSystem.prototype._isVisible = function () {
  80080. if (!this._isEnabled || !this._scene.activeCamera) {
  80081. return false;
  80082. }
  80083. var emitterPosition = this.getEmitterPosition();
  80084. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80085. var distance = direction.length();
  80086. direction.normalize();
  80087. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80088. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80089. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80090. };
  80091. LensFlareSystem.prototype.render = function () {
  80092. if (!this._effect.isReady() || !this._scene.activeCamera)
  80093. return false;
  80094. var engine = this._scene.getEngine();
  80095. var viewport = this._scene.activeCamera.viewport;
  80096. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80097. // Position
  80098. if (!this.computeEffectivePosition(globalViewport)) {
  80099. return false;
  80100. }
  80101. // Visibility
  80102. if (!this._isVisible()) {
  80103. return false;
  80104. }
  80105. // Intensity
  80106. var awayX;
  80107. var awayY;
  80108. if (this._positionX < this.borderLimit + globalViewport.x) {
  80109. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80110. }
  80111. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80112. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80113. }
  80114. else {
  80115. awayX = 0;
  80116. }
  80117. if (this._positionY < this.borderLimit + globalViewport.y) {
  80118. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80119. }
  80120. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80121. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80122. }
  80123. else {
  80124. awayY = 0;
  80125. }
  80126. var away = (awayX > awayY) ? awayX : awayY;
  80127. away -= this.viewportBorder;
  80128. if (away > this.borderLimit) {
  80129. away = this.borderLimit;
  80130. }
  80131. var intensity = 1.0 - (away / this.borderLimit);
  80132. if (intensity < 0) {
  80133. return false;
  80134. }
  80135. if (intensity > 1.0) {
  80136. intensity = 1.0;
  80137. }
  80138. if (this.viewportBorder > 0) {
  80139. globalViewport.x += this.viewportBorder;
  80140. globalViewport.y += this.viewportBorder;
  80141. globalViewport.width -= this.viewportBorder * 2;
  80142. globalViewport.height -= this.viewportBorder * 2;
  80143. this._positionX -= this.viewportBorder;
  80144. this._positionY -= this.viewportBorder;
  80145. }
  80146. // Position
  80147. var centerX = globalViewport.x + globalViewport.width / 2;
  80148. var centerY = globalViewport.y + globalViewport.height / 2;
  80149. var distX = centerX - this._positionX;
  80150. var distY = centerY - this._positionY;
  80151. // Effects
  80152. engine.enableEffect(this._effect);
  80153. engine.setState(false);
  80154. engine.setDepthBuffer(false);
  80155. // VBOs
  80156. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80157. // Flares
  80158. for (var index = 0; index < this.lensFlares.length; index++) {
  80159. var flare = this.lensFlares[index];
  80160. engine.setAlphaMode(flare.alphaMode);
  80161. var x = centerX - (distX * flare.position);
  80162. var y = centerY - (distY * flare.position);
  80163. var cw = flare.size;
  80164. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80165. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80166. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80167. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80168. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80169. // Texture
  80170. this._effect.setTexture("textureSampler", flare.texture);
  80171. // Color
  80172. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80173. // Draw order
  80174. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80175. }
  80176. engine.setDepthBuffer(true);
  80177. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80178. return true;
  80179. };
  80180. LensFlareSystem.prototype.dispose = function () {
  80181. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80182. if (vertexBuffer) {
  80183. vertexBuffer.dispose();
  80184. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80185. }
  80186. if (this._indexBuffer) {
  80187. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80188. this._indexBuffer = null;
  80189. }
  80190. while (this.lensFlares.length) {
  80191. this.lensFlares[0].dispose();
  80192. }
  80193. // Remove from scene
  80194. var index = this._scene.lensFlareSystems.indexOf(this);
  80195. this._scene.lensFlareSystems.splice(index, 1);
  80196. };
  80197. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80198. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80199. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80200. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80201. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80202. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80203. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80204. var parsedFlare = parsedLensFlareSystem.flares[index];
  80205. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80206. }
  80207. return lensFlareSystem;
  80208. };
  80209. LensFlareSystem.prototype.serialize = function () {
  80210. var serializationObject = {};
  80211. serializationObject.id = this.id;
  80212. serializationObject.name = this.name;
  80213. serializationObject.emitterId = this.getEmitter().id;
  80214. serializationObject.borderLimit = this.borderLimit;
  80215. serializationObject.flares = [];
  80216. for (var index = 0; index < this.lensFlares.length; index++) {
  80217. var flare = this.lensFlares[index];
  80218. serializationObject.flares.push({
  80219. size: flare.size,
  80220. position: flare.position,
  80221. color: flare.color.asArray(),
  80222. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80223. });
  80224. }
  80225. return serializationObject;
  80226. };
  80227. return LensFlareSystem;
  80228. }());
  80229. BABYLON.LensFlareSystem = LensFlareSystem;
  80230. })(BABYLON || (BABYLON = {}));
  80231. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80232. var BABYLON;
  80233. (function (BABYLON) {
  80234. /**
  80235. * This is a holder class for the physics joint created by the physics plugin.
  80236. * It holds a set of functions to control the underlying joint.
  80237. */
  80238. var PhysicsJoint = /** @class */ (function () {
  80239. function PhysicsJoint(type, jointData) {
  80240. this.type = type;
  80241. this.jointData = jointData;
  80242. jointData.nativeParams = jointData.nativeParams || {};
  80243. }
  80244. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80245. get: function () {
  80246. return this._physicsJoint;
  80247. },
  80248. set: function (newJoint) {
  80249. if (this._physicsJoint) {
  80250. //remove from the wolrd
  80251. }
  80252. this._physicsJoint = newJoint;
  80253. },
  80254. enumerable: true,
  80255. configurable: true
  80256. });
  80257. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80258. set: function (physicsPlugin) {
  80259. this._physicsPlugin = physicsPlugin;
  80260. },
  80261. enumerable: true,
  80262. configurable: true
  80263. });
  80264. /**
  80265. * Execute a function that is physics-plugin specific.
  80266. * @param {Function} func the function that will be executed.
  80267. * It accepts two parameters: the physics world and the physics joint.
  80268. */
  80269. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80270. func(this._physicsPlugin.world, this._physicsJoint);
  80271. };
  80272. //TODO check if the native joints are the same
  80273. //Joint Types
  80274. PhysicsJoint.DistanceJoint = 0;
  80275. PhysicsJoint.HingeJoint = 1;
  80276. PhysicsJoint.BallAndSocketJoint = 2;
  80277. PhysicsJoint.WheelJoint = 3;
  80278. PhysicsJoint.SliderJoint = 4;
  80279. //OIMO
  80280. PhysicsJoint.PrismaticJoint = 5;
  80281. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80282. PhysicsJoint.UniversalJoint = 6;
  80283. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80284. //Cannon
  80285. //Similar to a Ball-Joint. Different in params
  80286. PhysicsJoint.PointToPointJoint = 8;
  80287. //Cannon only at the moment
  80288. PhysicsJoint.SpringJoint = 9;
  80289. PhysicsJoint.LockJoint = 10;
  80290. return PhysicsJoint;
  80291. }());
  80292. BABYLON.PhysicsJoint = PhysicsJoint;
  80293. /**
  80294. * A class representing a physics distance joint.
  80295. */
  80296. var DistanceJoint = /** @class */ (function (_super) {
  80297. __extends(DistanceJoint, _super);
  80298. function DistanceJoint(jointData) {
  80299. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80300. }
  80301. /**
  80302. * Update the predefined distance.
  80303. */
  80304. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80305. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80306. };
  80307. return DistanceJoint;
  80308. }(PhysicsJoint));
  80309. BABYLON.DistanceJoint = DistanceJoint;
  80310. var MotorEnabledJoint = /** @class */ (function (_super) {
  80311. __extends(MotorEnabledJoint, _super);
  80312. function MotorEnabledJoint(type, jointData) {
  80313. return _super.call(this, type, jointData) || this;
  80314. }
  80315. /**
  80316. * Set the motor values.
  80317. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80318. * @param {number} force the force to apply
  80319. * @param {number} maxForce max force for this motor.
  80320. */
  80321. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  80322. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80323. };
  80324. /**
  80325. * Set the motor's limits.
  80326. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80327. */
  80328. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80329. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80330. };
  80331. return MotorEnabledJoint;
  80332. }(PhysicsJoint));
  80333. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  80334. /**
  80335. * This class represents a single hinge physics joint
  80336. */
  80337. var HingeJoint = /** @class */ (function (_super) {
  80338. __extends(HingeJoint, _super);
  80339. function HingeJoint(jointData) {
  80340. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  80341. }
  80342. /**
  80343. * Set the motor values.
  80344. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80345. * @param {number} force the force to apply
  80346. * @param {number} maxForce max force for this motor.
  80347. */
  80348. HingeJoint.prototype.setMotor = function (force, maxForce) {
  80349. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80350. };
  80351. /**
  80352. * Set the motor's limits.
  80353. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80354. */
  80355. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80356. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80357. };
  80358. return HingeJoint;
  80359. }(MotorEnabledJoint));
  80360. BABYLON.HingeJoint = HingeJoint;
  80361. /**
  80362. * This class represents a dual hinge physics joint (same as wheel joint)
  80363. */
  80364. var Hinge2Joint = /** @class */ (function (_super) {
  80365. __extends(Hinge2Joint, _super);
  80366. function Hinge2Joint(jointData) {
  80367. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  80368. }
  80369. /**
  80370. * Set the motor values.
  80371. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80372. * @param {number} force the force to apply
  80373. * @param {number} maxForce max force for this motor.
  80374. * @param {motorIndex} the motor's index, 0 or 1.
  80375. */
  80376. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  80377. if (motorIndex === void 0) { motorIndex = 0; }
  80378. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  80379. };
  80380. /**
  80381. * Set the motor limits.
  80382. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80383. * @param {number} upperLimit the upper limit
  80384. * @param {number} lowerLimit lower limit
  80385. * @param {motorIndex} the motor's index, 0 or 1.
  80386. */
  80387. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  80388. if (motorIndex === void 0) { motorIndex = 0; }
  80389. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  80390. };
  80391. return Hinge2Joint;
  80392. }(MotorEnabledJoint));
  80393. BABYLON.Hinge2Joint = Hinge2Joint;
  80394. })(BABYLON || (BABYLON = {}));
  80395. //# sourceMappingURL=babylon.physicsJoint.js.map
  80396. var BABYLON;
  80397. (function (BABYLON) {
  80398. var PhysicsImpostor = /** @class */ (function () {
  80399. function PhysicsImpostor(object, type, _options, _scene) {
  80400. if (_options === void 0) { _options = { mass: 0 }; }
  80401. var _this = this;
  80402. this.object = object;
  80403. this.type = type;
  80404. this._options = _options;
  80405. this._scene = _scene;
  80406. this._bodyUpdateRequired = false;
  80407. this._onBeforePhysicsStepCallbacks = new Array();
  80408. this._onAfterPhysicsStepCallbacks = new Array();
  80409. this._onPhysicsCollideCallbacks = [];
  80410. this._deltaPosition = BABYLON.Vector3.Zero();
  80411. this._isDisposed = false;
  80412. //temp variables for parent rotation calculations
  80413. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  80414. this._tmpQuat = new BABYLON.Quaternion();
  80415. this._tmpQuat2 = new BABYLON.Quaternion();
  80416. /**
  80417. * this function is executed by the physics engine.
  80418. */
  80419. this.beforeStep = function () {
  80420. if (!_this._physicsEngine) {
  80421. return;
  80422. }
  80423. _this.object.translate(_this._deltaPosition, -1);
  80424. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  80425. _this.object.computeWorldMatrix(false);
  80426. if (_this.object.parent && _this.object.rotationQuaternion) {
  80427. _this.getParentsRotation();
  80428. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  80429. }
  80430. else {
  80431. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  80432. }
  80433. if (!_this._options.disableBidirectionalTransformation) {
  80434. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  80435. }
  80436. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  80437. func(_this);
  80438. });
  80439. };
  80440. /**
  80441. * this function is executed by the physics engine.
  80442. */
  80443. this.afterStep = function () {
  80444. if (!_this._physicsEngine) {
  80445. return;
  80446. }
  80447. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  80448. func(_this);
  80449. });
  80450. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  80451. // object has now its world rotation. needs to be converted to local.
  80452. if (_this.object.parent && _this.object.rotationQuaternion) {
  80453. _this.getParentsRotation();
  80454. _this._tmpQuat.conjugateInPlace();
  80455. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  80456. }
  80457. // take the position set and make it the absolute position of this object.
  80458. _this.object.setAbsolutePosition(_this.object.position);
  80459. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  80460. _this.object.translate(_this._deltaPosition, 1);
  80461. };
  80462. /**
  80463. * Legacy collision detection event support
  80464. */
  80465. this.onCollideEvent = null;
  80466. //event and body object due to cannon's event-based architecture.
  80467. this.onCollide = function (e) {
  80468. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  80469. return;
  80470. }
  80471. if (!_this._physicsEngine) {
  80472. return;
  80473. }
  80474. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  80475. if (otherImpostor) {
  80476. // Legacy collision detection event support
  80477. if (_this.onCollideEvent) {
  80478. _this.onCollideEvent(_this, otherImpostor);
  80479. }
  80480. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  80481. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  80482. }).forEach(function (obj) {
  80483. obj.callback(_this, otherImpostor);
  80484. });
  80485. }
  80486. };
  80487. //sanity check!
  80488. if (!this.object) {
  80489. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  80490. return;
  80491. }
  80492. //legacy support for old syntax.
  80493. if (!this._scene && object.getScene) {
  80494. this._scene = object.getScene();
  80495. }
  80496. if (!this._scene) {
  80497. return;
  80498. }
  80499. this._physicsEngine = this._scene.getPhysicsEngine();
  80500. if (!this._physicsEngine) {
  80501. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80502. }
  80503. else {
  80504. //set the object's quaternion, if not set
  80505. if (!this.object.rotationQuaternion) {
  80506. if (this.object.rotation) {
  80507. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80508. }
  80509. else {
  80510. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80511. }
  80512. }
  80513. //default options params
  80514. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80515. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80516. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80517. this._joints = [];
  80518. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80519. if (!this.object.parent || this._options.ignoreParent) {
  80520. this._init();
  80521. }
  80522. else if (this.object.parent.physicsImpostor) {
  80523. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80524. }
  80525. }
  80526. }
  80527. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80528. get: function () {
  80529. return this._isDisposed;
  80530. },
  80531. enumerable: true,
  80532. configurable: true
  80533. });
  80534. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80535. get: function () {
  80536. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80537. },
  80538. set: function (value) {
  80539. this.setMass(value);
  80540. },
  80541. enumerable: true,
  80542. configurable: true
  80543. });
  80544. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80545. get: function () {
  80546. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80547. },
  80548. set: function (value) {
  80549. if (!this._physicsEngine) {
  80550. return;
  80551. }
  80552. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80553. },
  80554. enumerable: true,
  80555. configurable: true
  80556. });
  80557. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80558. get: function () {
  80559. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80560. },
  80561. set: function (value) {
  80562. if (!this._physicsEngine) {
  80563. return;
  80564. }
  80565. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80566. },
  80567. enumerable: true,
  80568. configurable: true
  80569. });
  80570. /**
  80571. * This function will completly initialize this impostor.
  80572. * It will create a new body - but only if this mesh has no parent.
  80573. * If it has, this impostor will not be used other than to define the impostor
  80574. * of the child mesh.
  80575. */
  80576. PhysicsImpostor.prototype._init = function () {
  80577. if (!this._physicsEngine) {
  80578. return;
  80579. }
  80580. this._physicsEngine.removeImpostor(this);
  80581. this.physicsBody = null;
  80582. this._parent = this._parent || this._getPhysicsParent();
  80583. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80584. this._physicsEngine.addImpostor(this);
  80585. }
  80586. };
  80587. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80588. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80589. var parentMesh = this.object.parent;
  80590. return parentMesh.physicsImpostor;
  80591. }
  80592. return null;
  80593. };
  80594. /**
  80595. * Should a new body be generated.
  80596. */
  80597. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80598. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80599. };
  80600. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80601. this.forceUpdate();
  80602. };
  80603. /**
  80604. * Force a regeneration of this or the parent's impostor's body.
  80605. * Use under cautious - This will remove all joints already implemented.
  80606. */
  80607. PhysicsImpostor.prototype.forceUpdate = function () {
  80608. this._init();
  80609. if (this.parent && !this._options.ignoreParent) {
  80610. this.parent.forceUpdate();
  80611. }
  80612. };
  80613. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80614. /*public get mesh(): AbstractMesh {
  80615. return this._mesh;
  80616. }*/
  80617. /**
  80618. * Gets the body that holds this impostor. Either its own, or its parent.
  80619. */
  80620. get: function () {
  80621. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80622. },
  80623. /**
  80624. * Set the physics body. Used mainly by the physics engine/plugin
  80625. */
  80626. set: function (physicsBody) {
  80627. if (this._physicsBody && this._physicsEngine) {
  80628. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80629. }
  80630. this._physicsBody = physicsBody;
  80631. this.resetUpdateFlags();
  80632. },
  80633. enumerable: true,
  80634. configurable: true
  80635. });
  80636. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80637. get: function () {
  80638. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80639. },
  80640. set: function (value) {
  80641. this._parent = value;
  80642. },
  80643. enumerable: true,
  80644. configurable: true
  80645. });
  80646. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80647. this._bodyUpdateRequired = false;
  80648. };
  80649. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80650. if (this.object.getBoundingInfo) {
  80651. var q = this.object.rotationQuaternion;
  80652. //reset rotation
  80653. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80654. //calculate the world matrix with no rotation
  80655. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80656. var boundingInfo = this.object.getBoundingInfo();
  80657. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80658. //bring back the rotation
  80659. this.object.rotationQuaternion = q;
  80660. //calculate the world matrix with the new rotation
  80661. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80662. return size;
  80663. }
  80664. else {
  80665. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80666. }
  80667. };
  80668. PhysicsImpostor.prototype.getObjectCenter = function () {
  80669. if (this.object.getBoundingInfo) {
  80670. var boundingInfo = this.object.getBoundingInfo();
  80671. return boundingInfo.boundingBox.centerWorld;
  80672. }
  80673. else {
  80674. return this.object.position;
  80675. }
  80676. };
  80677. /**
  80678. * Get a specific parametes from the options parameter.
  80679. */
  80680. PhysicsImpostor.prototype.getParam = function (paramName) {
  80681. return this._options[paramName];
  80682. };
  80683. /**
  80684. * Sets a specific parameter in the options given to the physics plugin
  80685. */
  80686. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80687. this._options[paramName] = value;
  80688. this._bodyUpdateRequired = true;
  80689. };
  80690. /**
  80691. * Specifically change the body's mass option. Won't recreate the physics body object
  80692. */
  80693. PhysicsImpostor.prototype.setMass = function (mass) {
  80694. if (this.getParam("mass") !== mass) {
  80695. this.setParam("mass", mass);
  80696. }
  80697. if (this._physicsEngine) {
  80698. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80699. }
  80700. };
  80701. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80702. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80703. };
  80704. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80705. if (this._physicsEngine) {
  80706. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80707. }
  80708. };
  80709. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80710. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80711. };
  80712. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80713. if (this._physicsEngine) {
  80714. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80715. }
  80716. };
  80717. /**
  80718. * Execute a function with the physics plugin native code.
  80719. * Provide a function the will have two variables - the world object and the physics body object.
  80720. */
  80721. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80722. if (this._physicsEngine) {
  80723. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80724. }
  80725. };
  80726. /**
  80727. * Register a function that will be executed before the physics world is stepping forward.
  80728. */
  80729. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80730. this._onBeforePhysicsStepCallbacks.push(func);
  80731. };
  80732. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80733. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80734. if (index > -1) {
  80735. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80736. }
  80737. else {
  80738. BABYLON.Tools.Warn("Function to remove was not found");
  80739. }
  80740. };
  80741. /**
  80742. * Register a function that will be executed after the physics step
  80743. */
  80744. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80745. this._onAfterPhysicsStepCallbacks.push(func);
  80746. };
  80747. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80748. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80749. if (index > -1) {
  80750. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80751. }
  80752. else {
  80753. BABYLON.Tools.Warn("Function to remove was not found");
  80754. }
  80755. };
  80756. /**
  80757. * register a function that will be executed when this impostor collides against a different body.
  80758. */
  80759. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80760. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80761. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80762. };
  80763. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80764. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80765. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80766. if (index > -1) {
  80767. this._onPhysicsCollideCallbacks.splice(index, 1);
  80768. }
  80769. else {
  80770. BABYLON.Tools.Warn("Function to remove was not found");
  80771. }
  80772. };
  80773. PhysicsImpostor.prototype.getParentsRotation = function () {
  80774. var parent = this.object.parent;
  80775. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80776. while (parent) {
  80777. if (parent.rotationQuaternion) {
  80778. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80779. }
  80780. else {
  80781. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80782. }
  80783. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80784. parent = parent.parent;
  80785. }
  80786. return this._tmpQuat;
  80787. };
  80788. /**
  80789. * Apply a force
  80790. */
  80791. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80792. if (this._physicsEngine) {
  80793. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80794. }
  80795. return this;
  80796. };
  80797. /**
  80798. * Apply an impulse
  80799. */
  80800. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80801. if (this._physicsEngine) {
  80802. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80803. }
  80804. return this;
  80805. };
  80806. /**
  80807. * A help function to create a joint.
  80808. */
  80809. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80810. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80811. this.addJoint(otherImpostor, joint);
  80812. return this;
  80813. };
  80814. /**
  80815. * Add a joint to this impostor with a different impostor.
  80816. */
  80817. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80818. this._joints.push({
  80819. otherImpostor: otherImpostor,
  80820. joint: joint
  80821. });
  80822. if (this._physicsEngine) {
  80823. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80824. }
  80825. return this;
  80826. };
  80827. /**
  80828. * Will keep this body still, in a sleep mode.
  80829. */
  80830. PhysicsImpostor.prototype.sleep = function () {
  80831. if (this._physicsEngine) {
  80832. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80833. }
  80834. return this;
  80835. };
  80836. /**
  80837. * Wake the body up.
  80838. */
  80839. PhysicsImpostor.prototype.wakeUp = function () {
  80840. if (this._physicsEngine) {
  80841. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80842. }
  80843. return this;
  80844. };
  80845. PhysicsImpostor.prototype.clone = function (newObject) {
  80846. if (!newObject)
  80847. return null;
  80848. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80849. };
  80850. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  80851. var _this = this;
  80852. //no dispose if no physics engine is available.
  80853. if (!this._physicsEngine) {
  80854. return;
  80855. }
  80856. this._joints.forEach(function (j) {
  80857. if (_this._physicsEngine) {
  80858. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80859. }
  80860. });
  80861. //dispose the physics body
  80862. this._physicsEngine.removeImpostor(this);
  80863. if (this.parent) {
  80864. this.parent.forceUpdate();
  80865. }
  80866. else {
  80867. /*this._object.getChildMeshes().forEach(function(mesh) {
  80868. if (mesh.physicsImpostor) {
  80869. if (disposeChildren) {
  80870. mesh.physicsImpostor.dispose();
  80871. mesh.physicsImpostor = null;
  80872. }
  80873. }
  80874. })*/
  80875. }
  80876. this._isDisposed = true;
  80877. };
  80878. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80879. this._deltaPosition.copyFrom(position);
  80880. };
  80881. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80882. if (!this._deltaRotation) {
  80883. this._deltaRotation = new BABYLON.Quaternion();
  80884. }
  80885. this._deltaRotation.copyFrom(rotation);
  80886. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80887. };
  80888. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80889. if (this._physicsEngine) {
  80890. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80891. }
  80892. return this;
  80893. };
  80894. PhysicsImpostor.prototype.getRadius = function () {
  80895. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80896. };
  80897. /**
  80898. * Sync a bone with this impostor
  80899. * @param bone The bone to sync to the impostor.
  80900. * @param boneMesh The mesh that the bone is influencing.
  80901. * @param jointPivot The pivot of the joint / bone in local space.
  80902. * @param distToJoint Optional distance from the impostor to the joint.
  80903. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80904. */
  80905. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80906. var tempVec = PhysicsImpostor._tmpVecs[0];
  80907. var mesh = this.object;
  80908. if (mesh.rotationQuaternion) {
  80909. if (adjustRotation) {
  80910. var tempQuat = PhysicsImpostor._tmpQuat;
  80911. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  80912. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  80913. }
  80914. else {
  80915. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  80916. }
  80917. }
  80918. tempVec.x = 0;
  80919. tempVec.y = 0;
  80920. tempVec.z = 0;
  80921. if (jointPivot) {
  80922. tempVec.x = jointPivot.x;
  80923. tempVec.y = jointPivot.y;
  80924. tempVec.z = jointPivot.z;
  80925. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80926. if (distToJoint === undefined || distToJoint === null) {
  80927. distToJoint = jointPivot.length();
  80928. }
  80929. tempVec.x *= distToJoint;
  80930. tempVec.y *= distToJoint;
  80931. tempVec.z *= distToJoint;
  80932. }
  80933. if (bone.getParent()) {
  80934. tempVec.addInPlace(mesh.getAbsolutePosition());
  80935. bone.setAbsolutePosition(tempVec, boneMesh);
  80936. }
  80937. else {
  80938. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80939. boneMesh.position.x -= tempVec.x;
  80940. boneMesh.position.y -= tempVec.y;
  80941. boneMesh.position.z -= tempVec.z;
  80942. }
  80943. };
  80944. /**
  80945. * Sync impostor to a bone
  80946. * @param bone The bone that the impostor will be synced to.
  80947. * @param boneMesh The mesh that the bone is influencing.
  80948. * @param jointPivot The pivot of the joint / bone in local space.
  80949. * @param distToJoint Optional distance from the impostor to the joint.
  80950. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80951. * @param boneAxis Optional vector3 axis the bone is aligned with
  80952. */
  80953. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80954. var mesh = this.object;
  80955. if (mesh.rotationQuaternion) {
  80956. if (adjustRotation) {
  80957. var tempQuat = PhysicsImpostor._tmpQuat;
  80958. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80959. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80960. }
  80961. else {
  80962. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80963. }
  80964. }
  80965. var pos = PhysicsImpostor._tmpVecs[0];
  80966. var boneDir = PhysicsImpostor._tmpVecs[1];
  80967. if (!boneAxis) {
  80968. boneAxis = PhysicsImpostor._tmpVecs[2];
  80969. boneAxis.x = 0;
  80970. boneAxis.y = 1;
  80971. boneAxis.z = 0;
  80972. }
  80973. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80974. bone.getAbsolutePositionToRef(boneMesh, pos);
  80975. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80976. distToJoint = jointPivot.length();
  80977. }
  80978. if (distToJoint !== undefined && distToJoint !== null) {
  80979. pos.x += boneDir.x * distToJoint;
  80980. pos.y += boneDir.y * distToJoint;
  80981. pos.z += boneDir.z * distToJoint;
  80982. }
  80983. mesh.setAbsolutePosition(pos);
  80984. };
  80985. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80986. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80987. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80988. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80989. //Impostor types
  80990. PhysicsImpostor.NoImpostor = 0;
  80991. PhysicsImpostor.SphereImpostor = 1;
  80992. PhysicsImpostor.BoxImpostor = 2;
  80993. PhysicsImpostor.PlaneImpostor = 3;
  80994. PhysicsImpostor.MeshImpostor = 4;
  80995. PhysicsImpostor.CylinderImpostor = 7;
  80996. PhysicsImpostor.ParticleImpostor = 8;
  80997. PhysicsImpostor.HeightmapImpostor = 9;
  80998. return PhysicsImpostor;
  80999. }());
  81000. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81001. })(BABYLON || (BABYLON = {}));
  81002. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81003. var BABYLON;
  81004. (function (BABYLON) {
  81005. var PhysicsEngine = /** @class */ (function () {
  81006. function PhysicsEngine(gravity, _physicsPlugin) {
  81007. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81008. this._physicsPlugin = _physicsPlugin;
  81009. //new methods and parameters
  81010. this._impostors = [];
  81011. this._joints = [];
  81012. if (!this._physicsPlugin.isSupported()) {
  81013. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81014. + "Please make sure it is included.");
  81015. }
  81016. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81017. this.setGravity(gravity);
  81018. this.setTimeStep();
  81019. }
  81020. PhysicsEngine.prototype.setGravity = function (gravity) {
  81021. this.gravity = gravity;
  81022. this._physicsPlugin.setGravity(this.gravity);
  81023. };
  81024. /**
  81025. * Set the time step of the physics engine.
  81026. * default is 1/60.
  81027. * To slow it down, enter 1/600 for example.
  81028. * To speed it up, 1/30
  81029. * @param {number} newTimeStep the new timestep to apply to this world.
  81030. */
  81031. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81032. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81033. this._physicsPlugin.setTimeStep(newTimeStep);
  81034. };
  81035. /**
  81036. * Get the time step of the physics engine.
  81037. */
  81038. PhysicsEngine.prototype.getTimeStep = function () {
  81039. return this._physicsPlugin.getTimeStep();
  81040. };
  81041. PhysicsEngine.prototype.dispose = function () {
  81042. this._impostors.forEach(function (impostor) {
  81043. impostor.dispose();
  81044. });
  81045. this._physicsPlugin.dispose();
  81046. };
  81047. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81048. return this._physicsPlugin.name;
  81049. };
  81050. /**
  81051. * Adding a new impostor for the impostor tracking.
  81052. * This will be done by the impostor itself.
  81053. * @param {PhysicsImpostor} impostor the impostor to add
  81054. */
  81055. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81056. impostor.uniqueId = this._impostors.push(impostor);
  81057. //if no parent, generate the body
  81058. if (!impostor.parent) {
  81059. this._physicsPlugin.generatePhysicsBody(impostor);
  81060. }
  81061. };
  81062. /**
  81063. * Remove an impostor from the engine.
  81064. * This impostor and its mesh will not longer be updated by the physics engine.
  81065. * @param {PhysicsImpostor} impostor the impostor to remove
  81066. */
  81067. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81068. var index = this._impostors.indexOf(impostor);
  81069. if (index > -1) {
  81070. var removed = this._impostors.splice(index, 1);
  81071. //Is it needed?
  81072. if (removed.length) {
  81073. //this will also remove it from the world.
  81074. removed[0].physicsBody = null;
  81075. }
  81076. }
  81077. };
  81078. /**
  81079. * Add a joint to the physics engine
  81080. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81081. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81082. * @param {PhysicsJoint} the joint that will connect both impostors.
  81083. */
  81084. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81085. var impostorJoint = {
  81086. mainImpostor: mainImpostor,
  81087. connectedImpostor: connectedImpostor,
  81088. joint: joint
  81089. };
  81090. joint.physicsPlugin = this._physicsPlugin;
  81091. this._joints.push(impostorJoint);
  81092. this._physicsPlugin.generateJoint(impostorJoint);
  81093. };
  81094. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81095. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81096. return (impostorJoint.connectedImpostor === connectedImpostor
  81097. && impostorJoint.joint === joint
  81098. && impostorJoint.mainImpostor === mainImpostor);
  81099. });
  81100. if (matchingJoints.length) {
  81101. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81102. //TODO remove it from the list as well
  81103. }
  81104. };
  81105. /**
  81106. * Called by the scene. no need to call it.
  81107. */
  81108. PhysicsEngine.prototype._step = function (delta) {
  81109. var _this = this;
  81110. //check if any mesh has no body / requires an update
  81111. this._impostors.forEach(function (impostor) {
  81112. if (impostor.isBodyInitRequired()) {
  81113. _this._physicsPlugin.generatePhysicsBody(impostor);
  81114. }
  81115. });
  81116. if (delta > 0.1) {
  81117. delta = 0.1;
  81118. }
  81119. else if (delta <= 0) {
  81120. delta = 1.0 / 60.0;
  81121. }
  81122. this._physicsPlugin.executeStep(delta, this._impostors);
  81123. };
  81124. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81125. return this._physicsPlugin;
  81126. };
  81127. PhysicsEngine.prototype.getImpostors = function () {
  81128. return this._impostors;
  81129. };
  81130. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81131. for (var i = 0; i < this._impostors.length; ++i) {
  81132. if (this._impostors[i].object === object) {
  81133. return this._impostors[i];
  81134. }
  81135. }
  81136. return null;
  81137. };
  81138. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81139. for (var i = 0; i < this._impostors.length; ++i) {
  81140. if (this._impostors[i].physicsBody === body) {
  81141. return this._impostors[i];
  81142. }
  81143. }
  81144. return null;
  81145. };
  81146. // Statics
  81147. PhysicsEngine.Epsilon = 0.001;
  81148. return PhysicsEngine;
  81149. }());
  81150. BABYLON.PhysicsEngine = PhysicsEngine;
  81151. })(BABYLON || (BABYLON = {}));
  81152. //# sourceMappingURL=babylon.physicsEngine.js.map
  81153. var BABYLON;
  81154. (function (BABYLON) {
  81155. var PhysicsHelper = /** @class */ (function () {
  81156. function PhysicsHelper(scene) {
  81157. this._scene = scene;
  81158. this._physicsEngine = this._scene.getPhysicsEngine();
  81159. if (!this._physicsEngine) {
  81160. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81161. }
  81162. }
  81163. /**
  81164. * @param {Vector3} origin the origin of the explosion
  81165. * @param {number} radius the explosion radius
  81166. * @param {number} strength the explosion strength
  81167. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81168. */
  81169. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81170. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81171. if (!this._physicsEngine) {
  81172. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81173. return null;
  81174. }
  81175. var impostors = this._physicsEngine.getImpostors();
  81176. if (impostors.length === 0) {
  81177. return null;
  81178. }
  81179. var event = new PhysicsRadialExplosionEvent(this._scene);
  81180. impostors.forEach(function (impostor) {
  81181. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81182. if (!impostorForceAndContactPoint) {
  81183. return;
  81184. }
  81185. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81186. });
  81187. event.dispose(false);
  81188. return event;
  81189. };
  81190. /**
  81191. * @param {Vector3} origin the origin of the explosion
  81192. * @param {number} radius the explosion radius
  81193. * @param {number} strength the explosion strength
  81194. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81195. */
  81196. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81197. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81198. if (!this._physicsEngine) {
  81199. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81200. return null;
  81201. }
  81202. var impostors = this._physicsEngine.getImpostors();
  81203. if (impostors.length === 0) {
  81204. return null;
  81205. }
  81206. var event = new PhysicsRadialExplosionEvent(this._scene);
  81207. impostors.forEach(function (impostor) {
  81208. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81209. if (!impostorForceAndContactPoint) {
  81210. return;
  81211. }
  81212. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81213. });
  81214. event.dispose(false);
  81215. return event;
  81216. };
  81217. /**
  81218. * @param {Vector3} origin the origin of the explosion
  81219. * @param {number} radius the explosion radius
  81220. * @param {number} strength the explosion strength
  81221. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81222. */
  81223. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81224. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81225. if (!this._physicsEngine) {
  81226. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81227. return null;
  81228. }
  81229. var impostors = this._physicsEngine.getImpostors();
  81230. if (impostors.length === 0) {
  81231. return null;
  81232. }
  81233. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81234. event.dispose(false);
  81235. return event;
  81236. };
  81237. /**
  81238. * @param {Vector3} origin the origin of the updraft
  81239. * @param {number} radius the radius of the updraft
  81240. * @param {number} strength the strength of the updraft
  81241. * @param {number} height the height of the updraft
  81242. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81243. */
  81244. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81245. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81246. if (!this._physicsEngine) {
  81247. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81248. return null;
  81249. }
  81250. if (this._physicsEngine.getImpostors().length === 0) {
  81251. return null;
  81252. }
  81253. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81254. event.dispose(false);
  81255. return event;
  81256. };
  81257. /**
  81258. * @param {Vector3} origin the of the vortex
  81259. * @param {number} radius the radius of the vortex
  81260. * @param {number} strength the strength of the vortex
  81261. * @param {number} height the height of the vortex
  81262. */
  81263. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81264. if (!this._physicsEngine) {
  81265. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81266. return null;
  81267. }
  81268. if (this._physicsEngine.getImpostors().length === 0) {
  81269. return null;
  81270. }
  81271. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81272. event.dispose(false);
  81273. return event;
  81274. };
  81275. return PhysicsHelper;
  81276. }());
  81277. BABYLON.PhysicsHelper = PhysicsHelper;
  81278. /***** Radial explosion *****/
  81279. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81280. function PhysicsRadialExplosionEvent(scene) {
  81281. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81282. this._rays = [];
  81283. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81284. this._scene = scene;
  81285. }
  81286. /**
  81287. * Returns the data related to the radial explosion event (sphere & rays).
  81288. * @returns {PhysicsRadialExplosionEventData}
  81289. */
  81290. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81291. this._dataFetched = true;
  81292. return {
  81293. sphere: this._sphere,
  81294. rays: this._rays,
  81295. };
  81296. };
  81297. /**
  81298. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81299. * @param impostor
  81300. * @param {Vector3} origin the origin of the explosion
  81301. * @param {number} radius the explosion radius
  81302. * @param {number} strength the explosion strength
  81303. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81304. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81305. */
  81306. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81307. if (impostor.mass === 0) {
  81308. return null;
  81309. }
  81310. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81311. return null;
  81312. }
  81313. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81314. return null;
  81315. }
  81316. var impostorObjectCenter = impostor.getObjectCenter();
  81317. var direction = impostorObjectCenter.subtract(origin);
  81318. var ray = new BABYLON.Ray(origin, direction, radius);
  81319. this._rays.push(ray);
  81320. var hit = ray.intersectsMesh(impostor.object);
  81321. var contactPoint = hit.pickedPoint;
  81322. if (!contactPoint) {
  81323. return null;
  81324. }
  81325. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  81326. if (distanceFromOrigin > radius) {
  81327. return null;
  81328. }
  81329. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  81330. ? strength
  81331. : strength * (1 - (distanceFromOrigin / radius));
  81332. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81333. return { force: force, contactPoint: contactPoint };
  81334. };
  81335. /**
  81336. * Disposes the sphere.
  81337. * @param {bolean} force
  81338. */
  81339. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  81340. var _this = this;
  81341. if (force === void 0) { force = true; }
  81342. if (force) {
  81343. this._sphere.dispose();
  81344. }
  81345. else {
  81346. setTimeout(function () {
  81347. if (!_this._dataFetched) {
  81348. _this._sphere.dispose();
  81349. }
  81350. }, 0);
  81351. }
  81352. };
  81353. /*** Helpers ***/
  81354. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  81355. if (!this._sphere) {
  81356. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  81357. this._sphere.isVisible = false;
  81358. }
  81359. };
  81360. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  81361. var impostorObject = impostor.object;
  81362. this._prepareSphere();
  81363. this._sphere.position = origin;
  81364. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  81365. this._sphere._updateBoundingInfo();
  81366. this._sphere.computeWorldMatrix(true);
  81367. return this._sphere.intersectsMesh(impostorObject, true);
  81368. };
  81369. return PhysicsRadialExplosionEvent;
  81370. }());
  81371. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  81372. /***** Gravitational Field *****/
  81373. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  81374. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  81375. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81376. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81377. this._physicsHelper = physicsHelper;
  81378. this._scene = scene;
  81379. this._origin = origin;
  81380. this._radius = radius;
  81381. this._strength = strength;
  81382. this._falloff = falloff;
  81383. this._tickCallback = this._tick.bind(this);
  81384. }
  81385. /**
  81386. * Returns the data related to the gravitational field event (sphere).
  81387. * @returns {PhysicsGravitationalFieldEventData}
  81388. */
  81389. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  81390. this._dataFetched = true;
  81391. return {
  81392. sphere: this._sphere,
  81393. };
  81394. };
  81395. /**
  81396. * Enables the gravitational field.
  81397. */
  81398. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  81399. this._tickCallback.call(this);
  81400. this._scene.registerBeforeRender(this._tickCallback);
  81401. };
  81402. /**
  81403. * Disables the gravitational field.
  81404. */
  81405. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  81406. this._scene.unregisterBeforeRender(this._tickCallback);
  81407. };
  81408. /**
  81409. * Disposes the sphere.
  81410. * @param {bolean} force
  81411. */
  81412. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  81413. var _this = this;
  81414. if (force === void 0) { force = true; }
  81415. if (force) {
  81416. this._sphere.dispose();
  81417. }
  81418. else {
  81419. setTimeout(function () {
  81420. if (!_this._dataFetched) {
  81421. _this._sphere.dispose();
  81422. }
  81423. }, 0);
  81424. }
  81425. };
  81426. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  81427. // Since the params won't change, we fetch the event only once
  81428. if (this._sphere) {
  81429. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81430. }
  81431. else {
  81432. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81433. if (radialExplosionEvent) {
  81434. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  81435. }
  81436. }
  81437. };
  81438. return PhysicsGravitationalFieldEvent;
  81439. }());
  81440. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  81441. /***** Updraft *****/
  81442. var PhysicsUpdraftEvent = /** @class */ (function () {
  81443. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  81444. this._scene = _scene;
  81445. this._origin = _origin;
  81446. this._radius = _radius;
  81447. this._strength = _strength;
  81448. this._height = _height;
  81449. this._updraftMode = _updraftMode;
  81450. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81451. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  81452. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81453. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81454. this._physicsEngine = this._scene.getPhysicsEngine();
  81455. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81456. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81457. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81458. this._originDirection = this._origin.subtract(this._originTop).normalize();
  81459. }
  81460. this._tickCallback = this._tick.bind(this);
  81461. }
  81462. /**
  81463. * Returns the data related to the updraft event (cylinder).
  81464. * @returns {PhysicsUpdraftEventData}
  81465. */
  81466. PhysicsUpdraftEvent.prototype.getData = function () {
  81467. this._dataFetched = true;
  81468. return {
  81469. cylinder: this._cylinder,
  81470. };
  81471. };
  81472. /**
  81473. * Enables the updraft.
  81474. */
  81475. PhysicsUpdraftEvent.prototype.enable = function () {
  81476. this._tickCallback.call(this);
  81477. this._scene.registerBeforeRender(this._tickCallback);
  81478. };
  81479. /**
  81480. * Disables the cortex.
  81481. */
  81482. PhysicsUpdraftEvent.prototype.disable = function () {
  81483. this._scene.unregisterBeforeRender(this._tickCallback);
  81484. };
  81485. /**
  81486. * Disposes the sphere.
  81487. * @param {bolean} force
  81488. */
  81489. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  81490. var _this = this;
  81491. if (force === void 0) { force = true; }
  81492. if (force) {
  81493. this._cylinder.dispose();
  81494. }
  81495. else {
  81496. setTimeout(function () {
  81497. if (!_this._dataFetched) {
  81498. _this._cylinder.dispose();
  81499. }
  81500. }, 0);
  81501. }
  81502. };
  81503. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81504. if (impostor.mass === 0) {
  81505. return null;
  81506. }
  81507. if (!this._intersectsWithCylinder(impostor)) {
  81508. return null;
  81509. }
  81510. var impostorObjectCenter = impostor.getObjectCenter();
  81511. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81512. var direction = this._originDirection;
  81513. }
  81514. else {
  81515. var direction = impostorObjectCenter.subtract(this._originTop);
  81516. }
  81517. var multiplier = this._strength * -1;
  81518. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81519. return { force: force, contactPoint: impostorObjectCenter };
  81520. };
  81521. PhysicsUpdraftEvent.prototype._tick = function () {
  81522. var _this = this;
  81523. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81524. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81525. if (!impostorForceAndContactPoint) {
  81526. return;
  81527. }
  81528. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81529. });
  81530. };
  81531. /*** Helpers ***/
  81532. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81533. if (!this._cylinder) {
  81534. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81535. height: this._height,
  81536. diameter: this._radius * 2,
  81537. }, this._scene);
  81538. this._cylinder.isVisible = false;
  81539. }
  81540. };
  81541. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81542. var impostorObject = impostor.object;
  81543. this._prepareCylinder();
  81544. this._cylinder.position = this._cylinderPosition;
  81545. return this._cylinder.intersectsMesh(impostorObject, true);
  81546. };
  81547. return PhysicsUpdraftEvent;
  81548. }());
  81549. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81550. /***** Vortex *****/
  81551. var PhysicsVortexEvent = /** @class */ (function () {
  81552. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81553. this._scene = _scene;
  81554. this._origin = _origin;
  81555. this._radius = _radius;
  81556. this._strength = _strength;
  81557. this._height = _height;
  81558. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81559. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81560. this._updraftMultiplier = 0.02;
  81561. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81562. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81563. this._physicsEngine = this._scene.getPhysicsEngine();
  81564. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81565. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81566. this._tickCallback = this._tick.bind(this);
  81567. }
  81568. /**
  81569. * Returns the data related to the vortex event (cylinder).
  81570. * @returns {PhysicsVortexEventData}
  81571. */
  81572. PhysicsVortexEvent.prototype.getData = function () {
  81573. this._dataFetched = true;
  81574. return {
  81575. cylinder: this._cylinder,
  81576. };
  81577. };
  81578. /**
  81579. * Enables the vortex.
  81580. */
  81581. PhysicsVortexEvent.prototype.enable = function () {
  81582. this._tickCallback.call(this);
  81583. this._scene.registerBeforeRender(this._tickCallback);
  81584. };
  81585. /**
  81586. * Disables the cortex.
  81587. */
  81588. PhysicsVortexEvent.prototype.disable = function () {
  81589. this._scene.unregisterBeforeRender(this._tickCallback);
  81590. };
  81591. /**
  81592. * Disposes the sphere.
  81593. * @param {bolean} force
  81594. */
  81595. PhysicsVortexEvent.prototype.dispose = function (force) {
  81596. var _this = this;
  81597. if (force === void 0) { force = true; }
  81598. if (force) {
  81599. this._cylinder.dispose();
  81600. }
  81601. else {
  81602. setTimeout(function () {
  81603. if (!_this._dataFetched) {
  81604. _this._cylinder.dispose();
  81605. }
  81606. }, 0);
  81607. }
  81608. };
  81609. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81610. if (impostor.mass === 0) {
  81611. return null;
  81612. }
  81613. if (!this._intersectsWithCylinder(impostor)) {
  81614. return null;
  81615. }
  81616. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81617. return null;
  81618. }
  81619. var impostorObjectCenter = impostor.getObjectCenter();
  81620. 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)
  81621. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81622. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81623. var hit = ray.intersectsMesh(impostor.object);
  81624. var contactPoint = hit.pickedPoint;
  81625. if (!contactPoint) {
  81626. return null;
  81627. }
  81628. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81629. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81630. var directionToOrigin = contactPoint.normalize();
  81631. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81632. directionToOrigin = directionToOrigin.negate();
  81633. }
  81634. // TODO: find a more physically based solution
  81635. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81636. var forceX = directionToOrigin.x * this._strength / 8;
  81637. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81638. var forceZ = directionToOrigin.z * this._strength / 8;
  81639. }
  81640. else {
  81641. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81642. var forceY = this._originTop.y * this._updraftMultiplier;
  81643. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81644. }
  81645. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81646. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81647. return { force: force, contactPoint: impostorObjectCenter };
  81648. };
  81649. PhysicsVortexEvent.prototype._tick = function () {
  81650. var _this = this;
  81651. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81652. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81653. if (!impostorForceAndContactPoint) {
  81654. return;
  81655. }
  81656. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81657. });
  81658. };
  81659. /*** Helpers ***/
  81660. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81661. if (!this._cylinder) {
  81662. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81663. height: this._height,
  81664. diameter: this._radius * 2,
  81665. }, this._scene);
  81666. this._cylinder.isVisible = false;
  81667. }
  81668. };
  81669. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81670. var impostorObject = impostor.object;
  81671. this._prepareCylinder();
  81672. this._cylinder.position = this._cylinderPosition;
  81673. return this._cylinder.intersectsMesh(impostorObject, true);
  81674. };
  81675. return PhysicsVortexEvent;
  81676. }());
  81677. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81678. /***** Enums *****/
  81679. /**
  81680. * The strenght of the force in correspondence to the distance of the affected object
  81681. */
  81682. var PhysicsRadialImpulseFalloff;
  81683. (function (PhysicsRadialImpulseFalloff) {
  81684. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81685. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81686. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81687. /**
  81688. * The strenght of the force in correspondence to the distance of the affected object
  81689. */
  81690. var PhysicsUpdraftMode;
  81691. (function (PhysicsUpdraftMode) {
  81692. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81693. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81694. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81695. })(BABYLON || (BABYLON = {}));
  81696. //# sourceMappingURL=babylon.physicsHelper.js.map
  81697. var BABYLON;
  81698. (function (BABYLON) {
  81699. var CannonJSPlugin = /** @class */ (function () {
  81700. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81701. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81702. if (iterations === void 0) { iterations = 10; }
  81703. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81704. this.name = "CannonJSPlugin";
  81705. this._physicsMaterials = new Array();
  81706. this._fixedTimeStep = 1 / 60;
  81707. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81708. this.BJSCANNON = CANNON;
  81709. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81710. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81711. this._tmpPosition = BABYLON.Vector3.Zero();
  81712. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81713. this._tmpUnityRotation = new BABYLON.Quaternion();
  81714. if (!this.isSupported()) {
  81715. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81716. return;
  81717. }
  81718. this._extendNamespace();
  81719. this.world = new this.BJSCANNON.World();
  81720. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81721. this.world.solver.iterations = iterations;
  81722. }
  81723. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81724. this.world.gravity.copy(gravity);
  81725. };
  81726. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81727. this._fixedTimeStep = timeStep;
  81728. };
  81729. CannonJSPlugin.prototype.getTimeStep = function () {
  81730. return this._fixedTimeStep;
  81731. };
  81732. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81733. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81734. };
  81735. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81736. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81737. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81738. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81739. };
  81740. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81741. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81742. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81743. impostor.physicsBody.applyForce(impulse, worldPoint);
  81744. };
  81745. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81746. //parent-child relationship. Does this impostor has a parent impostor?
  81747. if (impostor.parent) {
  81748. if (impostor.physicsBody) {
  81749. this.removePhysicsBody(impostor);
  81750. //TODO is that needed?
  81751. impostor.forceUpdate();
  81752. }
  81753. return;
  81754. }
  81755. //should a new body be created for this impostor?
  81756. if (impostor.isBodyInitRequired()) {
  81757. var shape = this._createShape(impostor);
  81758. //unregister events, if body is being changed
  81759. var oldBody = impostor.physicsBody;
  81760. if (oldBody) {
  81761. this.removePhysicsBody(impostor);
  81762. }
  81763. //create the body and material
  81764. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81765. var bodyCreationObject = {
  81766. mass: impostor.getParam("mass"),
  81767. material: material
  81768. };
  81769. // A simple extend, in case native options were used.
  81770. var nativeOptions = impostor.getParam("nativeOptions");
  81771. for (var key in nativeOptions) {
  81772. if (nativeOptions.hasOwnProperty(key)) {
  81773. bodyCreationObject[key] = nativeOptions[key];
  81774. }
  81775. }
  81776. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81777. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81778. this.world.addEventListener("preStep", impostor.beforeStep);
  81779. this.world.addEventListener("postStep", impostor.afterStep);
  81780. impostor.physicsBody.addShape(shape);
  81781. this.world.add(impostor.physicsBody);
  81782. //try to keep the body moving in the right direction by taking old properties.
  81783. //Should be tested!
  81784. if (oldBody) {
  81785. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81786. impostor.physicsBody[param].copy(oldBody[param]);
  81787. });
  81788. }
  81789. this._processChildMeshes(impostor);
  81790. }
  81791. //now update the body's transformation
  81792. this._updatePhysicsBodyTransformation(impostor);
  81793. };
  81794. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81795. var _this = this;
  81796. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81797. var currentRotation = mainImpostor.object.rotationQuaternion;
  81798. if (meshChildren.length) {
  81799. var processMesh = function (localPosition, mesh) {
  81800. if (!currentRotation || !mesh.rotationQuaternion) {
  81801. return;
  81802. }
  81803. var childImpostor = mesh.getPhysicsImpostor();
  81804. if (childImpostor) {
  81805. var parent = childImpostor.parent;
  81806. if (parent !== mainImpostor) {
  81807. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81808. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81809. if (childImpostor.physicsBody) {
  81810. _this.removePhysicsBody(childImpostor);
  81811. childImpostor.physicsBody = null;
  81812. }
  81813. childImpostor.parent = mainImpostor;
  81814. childImpostor.resetUpdateFlags();
  81815. 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));
  81816. //Add the mass of the children.
  81817. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81818. }
  81819. }
  81820. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81821. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81822. };
  81823. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81824. }
  81825. };
  81826. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81827. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81828. this.world.removeEventListener("preStep", impostor.beforeStep);
  81829. this.world.removeEventListener("postStep", impostor.afterStep);
  81830. this.world.remove(impostor.physicsBody);
  81831. };
  81832. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81833. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81834. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81835. if (!mainBody || !connectedBody) {
  81836. return;
  81837. }
  81838. var constraint;
  81839. var jointData = impostorJoint.joint.jointData;
  81840. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81841. var constraintData = {
  81842. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81843. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81844. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81845. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81846. maxForce: jointData.nativeParams.maxForce,
  81847. collideConnected: !!jointData.collision
  81848. };
  81849. switch (impostorJoint.joint.type) {
  81850. case BABYLON.PhysicsJoint.HingeJoint:
  81851. case BABYLON.PhysicsJoint.Hinge2Joint:
  81852. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81853. break;
  81854. case BABYLON.PhysicsJoint.DistanceJoint:
  81855. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81856. break;
  81857. case BABYLON.PhysicsJoint.SpringJoint:
  81858. var springData = jointData;
  81859. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81860. restLength: springData.length,
  81861. stiffness: springData.stiffness,
  81862. damping: springData.damping,
  81863. localAnchorA: constraintData.pivotA,
  81864. localAnchorB: constraintData.pivotB
  81865. });
  81866. break;
  81867. case BABYLON.PhysicsJoint.LockJoint:
  81868. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81869. break;
  81870. case BABYLON.PhysicsJoint.PointToPointJoint:
  81871. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81872. default:
  81873. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81874. break;
  81875. }
  81876. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81877. constraint.collideConnected = !!jointData.collision;
  81878. impostorJoint.joint.physicsJoint = constraint;
  81879. //don't add spring as constraint, as it is not one.
  81880. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81881. this.world.addConstraint(constraint);
  81882. }
  81883. else {
  81884. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81885. constraint.applyForce();
  81886. });
  81887. }
  81888. };
  81889. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81890. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81891. };
  81892. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81893. var index;
  81894. var mat;
  81895. for (index = 0; index < this._physicsMaterials.length; index++) {
  81896. mat = this._physicsMaterials[index];
  81897. if (mat.friction === friction && mat.restitution === restitution) {
  81898. return mat;
  81899. }
  81900. }
  81901. var currentMat = new this.BJSCANNON.Material(name);
  81902. currentMat.friction = friction;
  81903. currentMat.restitution = restitution;
  81904. this._physicsMaterials.push(currentMat);
  81905. return currentMat;
  81906. };
  81907. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  81908. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  81909. };
  81910. CannonJSPlugin.prototype._createShape = function (impostor) {
  81911. var object = impostor.object;
  81912. var returnValue;
  81913. var extendSize = impostor.getObjectExtendSize();
  81914. switch (impostor.type) {
  81915. case BABYLON.PhysicsImpostor.SphereImpostor:
  81916. var radiusX = extendSize.x;
  81917. var radiusY = extendSize.y;
  81918. var radiusZ = extendSize.z;
  81919. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  81920. break;
  81921. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81922. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81923. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81924. break;
  81925. case BABYLON.PhysicsImpostor.BoxImpostor:
  81926. var box = extendSize.scale(0.5);
  81927. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81928. break;
  81929. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81930. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81931. returnValue = new this.BJSCANNON.Plane();
  81932. break;
  81933. case BABYLON.PhysicsImpostor.MeshImpostor:
  81934. // should transform the vertex data to world coordinates!!
  81935. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81936. var rawFaces = object.getIndices ? object.getIndices() : [];
  81937. if (!rawVerts)
  81938. return;
  81939. // get only scale! so the object could transform correctly.
  81940. var oldPosition = object.position.clone();
  81941. var oldRotation = object.rotation && object.rotation.clone();
  81942. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81943. object.position.copyFromFloats(0, 0, 0);
  81944. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81945. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81946. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81947. var transform = object.computeWorldMatrix(true);
  81948. // convert rawVerts to object space
  81949. var temp = new Array();
  81950. var index;
  81951. for (index = 0; index < rawVerts.length; index += 3) {
  81952. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81953. }
  81954. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81955. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81956. //now set back the transformation!
  81957. object.position.copyFrom(oldPosition);
  81958. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81959. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81960. break;
  81961. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81962. var oldPosition2 = object.position.clone();
  81963. var oldRotation2 = object.rotation && object.rotation.clone();
  81964. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81965. object.position.copyFromFloats(0, 0, 0);
  81966. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81967. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81968. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81969. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81970. returnValue = this._createHeightmap(object);
  81971. object.position.copyFrom(oldPosition2);
  81972. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81973. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81974. object.computeWorldMatrix(true);
  81975. break;
  81976. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81977. returnValue = new this.BJSCANNON.Particle();
  81978. break;
  81979. }
  81980. return returnValue;
  81981. };
  81982. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81983. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81984. var transform = object.computeWorldMatrix(true);
  81985. // convert rawVerts to object space
  81986. var temp = new Array();
  81987. var index;
  81988. for (index = 0; index < pos.length; index += 3) {
  81989. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81990. }
  81991. pos = temp;
  81992. var matrix = new Array();
  81993. //For now pointDepth will not be used and will be automatically calculated.
  81994. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81995. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81996. var boundingInfo = object.getBoundingInfo();
  81997. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81998. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81999. var elementSize = dim * 2 / arraySize;
  82000. for (var i = 0; i < pos.length; i = i + 3) {
  82001. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82002. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82003. var y = -pos[i + 2] + minY;
  82004. if (!matrix[x]) {
  82005. matrix[x] = [];
  82006. }
  82007. if (!matrix[x][z]) {
  82008. matrix[x][z] = y;
  82009. }
  82010. matrix[x][z] = Math.max(y, matrix[x][z]);
  82011. }
  82012. for (var x = 0; x <= arraySize; ++x) {
  82013. if (!matrix[x]) {
  82014. var loc = 1;
  82015. while (!matrix[(x + loc) % arraySize]) {
  82016. loc++;
  82017. }
  82018. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82019. //console.log("missing x", x);
  82020. }
  82021. for (var z = 0; z <= arraySize; ++z) {
  82022. if (!matrix[x][z]) {
  82023. var loc = 1;
  82024. var newValue;
  82025. while (newValue === undefined) {
  82026. newValue = matrix[x][(z + loc++) % arraySize];
  82027. }
  82028. matrix[x][z] = newValue;
  82029. }
  82030. }
  82031. }
  82032. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82033. elementSize: elementSize
  82034. });
  82035. //For future reference, needed for body transformation
  82036. shape.minY = minY;
  82037. return shape;
  82038. };
  82039. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82040. var object = impostor.object;
  82041. //make sure it is updated...
  82042. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82043. // The delta between the mesh position and the mesh bounding box center
  82044. var bInfo = object.getBoundingInfo();
  82045. if (!bInfo)
  82046. return;
  82047. var center = impostor.getObjectCenter();
  82048. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82049. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82050. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82051. this._tmpPosition.copyFrom(center);
  82052. var quaternion = object.rotationQuaternion;
  82053. if (!quaternion) {
  82054. return;
  82055. }
  82056. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82057. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82058. //-90 DEG in X, precalculated
  82059. quaternion = quaternion.multiply(this._minus90X);
  82060. //Invert! (Precalculated, 90 deg in X)
  82061. //No need to clone. this will never change.
  82062. impostor.setDeltaRotation(this._plus90X);
  82063. }
  82064. //If it is a heightfield, if should be centered.
  82065. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82066. var mesh = object;
  82067. var boundingInfo = mesh.getBoundingInfo();
  82068. //calculate the correct body position:
  82069. var rotationQuaternion = mesh.rotationQuaternion;
  82070. mesh.rotationQuaternion = this._tmpUnityRotation;
  82071. mesh.computeWorldMatrix(true);
  82072. //get original center with no rotation
  82073. var c = center.clone();
  82074. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82075. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82076. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82077. mesh.setPreTransformMatrix(p);
  82078. mesh.computeWorldMatrix(true);
  82079. //calculate the translation
  82080. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82081. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82082. //add it inverted to the delta
  82083. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82084. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82085. //rotation is back
  82086. mesh.rotationQuaternion = rotationQuaternion;
  82087. mesh.setPreTransformMatrix(oldPivot);
  82088. mesh.computeWorldMatrix(true);
  82089. }
  82090. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82091. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82092. //this._tmpPosition.copyFrom(object.position);
  82093. }
  82094. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82095. //Now update the impostor object
  82096. impostor.physicsBody.position.copy(this._tmpPosition);
  82097. impostor.physicsBody.quaternion.copy(quaternion);
  82098. };
  82099. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82100. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82101. if (impostor.object.rotationQuaternion) {
  82102. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82103. }
  82104. };
  82105. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82106. impostor.physicsBody.position.copy(newPosition);
  82107. impostor.physicsBody.quaternion.copy(newRotation);
  82108. };
  82109. CannonJSPlugin.prototype.isSupported = function () {
  82110. return this.BJSCANNON !== undefined;
  82111. };
  82112. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82113. impostor.physicsBody.velocity.copy(velocity);
  82114. };
  82115. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82116. impostor.physicsBody.angularVelocity.copy(velocity);
  82117. };
  82118. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82119. var v = impostor.physicsBody.velocity;
  82120. if (!v) {
  82121. return null;
  82122. }
  82123. return new BABYLON.Vector3(v.x, v.y, v.z);
  82124. };
  82125. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82126. var v = impostor.physicsBody.angularVelocity;
  82127. if (!v) {
  82128. return null;
  82129. }
  82130. return new BABYLON.Vector3(v.x, v.y, v.z);
  82131. };
  82132. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82133. impostor.physicsBody.mass = mass;
  82134. impostor.physicsBody.updateMassProperties();
  82135. };
  82136. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82137. return impostor.physicsBody.mass;
  82138. };
  82139. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82140. return impostor.physicsBody.material.friction;
  82141. };
  82142. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82143. impostor.physicsBody.material.friction = friction;
  82144. };
  82145. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82146. return impostor.physicsBody.material.restitution;
  82147. };
  82148. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82149. impostor.physicsBody.material.restitution = restitution;
  82150. };
  82151. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82152. impostor.physicsBody.sleep();
  82153. };
  82154. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82155. impostor.physicsBody.wakeUp();
  82156. };
  82157. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82158. joint.physicsJoint.distance = maxDistance;
  82159. };
  82160. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82161. // if (!motorIndex) {
  82162. // joint.physicsJoint.enableMotor();
  82163. // }
  82164. // }
  82165. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82166. // if (!motorIndex) {
  82167. // joint.physicsJoint.disableMotor();
  82168. // }
  82169. // }
  82170. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82171. if (!motorIndex) {
  82172. joint.physicsJoint.enableMotor();
  82173. joint.physicsJoint.setMotorSpeed(speed);
  82174. if (maxForce) {
  82175. this.setLimit(joint, maxForce);
  82176. }
  82177. }
  82178. };
  82179. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82180. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82181. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82182. };
  82183. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82184. var body = impostor.physicsBody;
  82185. mesh.position.x = body.position.x;
  82186. mesh.position.y = body.position.y;
  82187. mesh.position.z = body.position.z;
  82188. if (mesh.rotationQuaternion) {
  82189. mesh.rotationQuaternion.x = body.quaternion.x;
  82190. mesh.rotationQuaternion.y = body.quaternion.y;
  82191. mesh.rotationQuaternion.z = body.quaternion.z;
  82192. mesh.rotationQuaternion.w = body.quaternion.w;
  82193. }
  82194. };
  82195. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82196. var shape = impostor.physicsBody.shapes[0];
  82197. return shape.boundingSphereRadius;
  82198. };
  82199. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82200. var shape = impostor.physicsBody.shapes[0];
  82201. result.x = shape.halfExtents.x * 2;
  82202. result.y = shape.halfExtents.y * 2;
  82203. result.z = shape.halfExtents.z * 2;
  82204. };
  82205. CannonJSPlugin.prototype.dispose = function () {
  82206. };
  82207. CannonJSPlugin.prototype._extendNamespace = function () {
  82208. //this will force cannon to execute at least one step when using interpolation
  82209. var step_tmp1 = new this.BJSCANNON.Vec3();
  82210. var Engine = this.BJSCANNON;
  82211. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82212. maxSubSteps = maxSubSteps || 10;
  82213. timeSinceLastCalled = timeSinceLastCalled || 0;
  82214. if (timeSinceLastCalled === 0) {
  82215. this.internalStep(dt);
  82216. this.time += dt;
  82217. }
  82218. else {
  82219. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82220. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82221. var t0 = performance.now();
  82222. for (var i = 0; i !== internalSteps; i++) {
  82223. this.internalStep(dt);
  82224. if (performance.now() - t0 > dt * 1000) {
  82225. break;
  82226. }
  82227. }
  82228. this.time += timeSinceLastCalled;
  82229. var h = this.time % dt;
  82230. var h_div_dt = h / dt;
  82231. var interpvelo = step_tmp1;
  82232. var bodies = this.bodies;
  82233. for (var j = 0; j !== bodies.length; j++) {
  82234. var b = bodies[j];
  82235. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82236. b.position.vsub(b.previousPosition, interpvelo);
  82237. interpvelo.scale(h_div_dt, interpvelo);
  82238. b.position.vadd(interpvelo, b.interpolatedPosition);
  82239. }
  82240. else {
  82241. b.interpolatedPosition.copy(b.position);
  82242. b.interpolatedQuaternion.copy(b.quaternion);
  82243. }
  82244. }
  82245. }
  82246. };
  82247. };
  82248. return CannonJSPlugin;
  82249. }());
  82250. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82251. })(BABYLON || (BABYLON = {}));
  82252. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82253. var BABYLON;
  82254. (function (BABYLON) {
  82255. var OimoJSPlugin = /** @class */ (function () {
  82256. function OimoJSPlugin(iterations) {
  82257. this.name = "OimoJSPlugin";
  82258. this._tmpImpostorsArray = [];
  82259. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82260. this.BJSOIMO = OIMO;
  82261. this.world = new this.BJSOIMO.World({
  82262. iterations: iterations
  82263. });
  82264. this.world.clear();
  82265. }
  82266. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82267. this.world.gravity.copy(gravity);
  82268. };
  82269. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82270. this.world.timeStep = timeStep;
  82271. };
  82272. OimoJSPlugin.prototype.getTimeStep = function () {
  82273. return this.world.timeStep;
  82274. };
  82275. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82276. var _this = this;
  82277. impostors.forEach(function (impostor) {
  82278. impostor.beforeStep();
  82279. });
  82280. this.world.step();
  82281. impostors.forEach(function (impostor) {
  82282. impostor.afterStep();
  82283. //update the ordered impostors array
  82284. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82285. });
  82286. //check for collisions
  82287. var contact = this.world.contacts;
  82288. while (contact !== null) {
  82289. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82290. contact = contact.next;
  82291. continue;
  82292. }
  82293. //is this body colliding with any other? get the impostor
  82294. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82295. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82296. if (!mainImpostor || !collidingImpostor) {
  82297. contact = contact.next;
  82298. continue;
  82299. }
  82300. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82301. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82302. contact = contact.next;
  82303. }
  82304. };
  82305. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82306. var mass = impostor.physicsBody.mass;
  82307. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82308. };
  82309. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82310. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82311. this.applyImpulse(impostor, force, contactPoint);
  82312. };
  82313. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82314. var _this = this;
  82315. //parent-child relationship. Does this impostor has a parent impostor?
  82316. if (impostor.parent) {
  82317. if (impostor.physicsBody) {
  82318. this.removePhysicsBody(impostor);
  82319. //TODO is that needed?
  82320. impostor.forceUpdate();
  82321. }
  82322. return;
  82323. }
  82324. if (impostor.isBodyInitRequired()) {
  82325. var bodyConfig = {
  82326. name: impostor.uniqueId,
  82327. //Oimo must have mass, also for static objects.
  82328. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  82329. size: [],
  82330. type: [],
  82331. pos: [],
  82332. posShape: [],
  82333. rot: [],
  82334. rotShape: [],
  82335. move: impostor.getParam("mass") !== 0,
  82336. density: impostor.getParam("mass"),
  82337. friction: impostor.getParam("friction"),
  82338. restitution: impostor.getParam("restitution"),
  82339. //Supporting older versions of Oimo
  82340. world: this.world
  82341. };
  82342. var impostors = [impostor];
  82343. var addToArray = function (parent) {
  82344. if (!parent.getChildMeshes)
  82345. return;
  82346. parent.getChildMeshes().forEach(function (m) {
  82347. if (m.physicsImpostor) {
  82348. impostors.push(m.physicsImpostor);
  82349. //m.physicsImpostor._init();
  82350. }
  82351. });
  82352. };
  82353. addToArray(impostor.object);
  82354. var checkWithEpsilon_1 = function (value) {
  82355. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  82356. };
  82357. impostors.forEach(function (i) {
  82358. if (!i.object.rotationQuaternion) {
  82359. return;
  82360. }
  82361. //get the correct bounding box
  82362. var oldQuaternion = i.object.rotationQuaternion;
  82363. var rot = oldQuaternion.toEulerAngles();
  82364. var extendSize = i.getObjectExtendSize();
  82365. var radToDeg = 57.295779513082320876;
  82366. if (i === impostor) {
  82367. var center = impostor.getObjectCenter();
  82368. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  82369. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  82370. //Can also use Array.prototype.push.apply
  82371. bodyConfig.pos.push(center.x);
  82372. bodyConfig.pos.push(center.y);
  82373. bodyConfig.pos.push(center.z);
  82374. bodyConfig.posShape.push(0, 0, 0);
  82375. //tmp solution
  82376. bodyConfig.rot.push(rot.x * radToDeg);
  82377. bodyConfig.rot.push(rot.y * radToDeg);
  82378. bodyConfig.rot.push(rot.z * radToDeg);
  82379. bodyConfig.rotShape.push(0, 0, 0);
  82380. }
  82381. else {
  82382. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  82383. bodyConfig.posShape.push(localPosition.x);
  82384. bodyConfig.posShape.push(localPosition.y);
  82385. bodyConfig.posShape.push(localPosition.z);
  82386. bodyConfig.pos.push(0, 0, 0);
  82387. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  82388. bodyConfig.rot.push(0);
  82389. bodyConfig.rot.push(0);
  82390. bodyConfig.rot.push(0);
  82391. bodyConfig.rotShape.push(rot.x * radToDeg);
  82392. bodyConfig.rotShape.push(rot.y * radToDeg);
  82393. bodyConfig.rotShape.push(rot.z * radToDeg);
  82394. }
  82395. // register mesh
  82396. switch (i.type) {
  82397. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82398. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  82399. case BABYLON.PhysicsImpostor.SphereImpostor:
  82400. var radiusX = extendSize.x;
  82401. var radiusY = extendSize.y;
  82402. var radiusZ = extendSize.z;
  82403. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  82404. bodyConfig.type.push('sphere');
  82405. //due to the way oimo works with compounds, add 3 times
  82406. bodyConfig.size.push(size);
  82407. bodyConfig.size.push(size);
  82408. bodyConfig.size.push(size);
  82409. break;
  82410. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82411. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  82412. var sizeY = checkWithEpsilon_1(extendSize.y);
  82413. bodyConfig.type.push('cylinder');
  82414. bodyConfig.size.push(sizeX);
  82415. bodyConfig.size.push(sizeY);
  82416. //due to the way oimo works with compounds, add one more value.
  82417. bodyConfig.size.push(sizeY);
  82418. break;
  82419. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82420. case BABYLON.PhysicsImpostor.BoxImpostor:
  82421. default:
  82422. var sizeX = checkWithEpsilon_1(extendSize.x);
  82423. var sizeY = checkWithEpsilon_1(extendSize.y);
  82424. var sizeZ = checkWithEpsilon_1(extendSize.z);
  82425. bodyConfig.type.push('box');
  82426. //if (i === impostor) {
  82427. bodyConfig.size.push(sizeX);
  82428. bodyConfig.size.push(sizeY);
  82429. bodyConfig.size.push(sizeZ);
  82430. //} else {
  82431. // bodyConfig.size.push(0,0,0);
  82432. //}
  82433. break;
  82434. }
  82435. //actually not needed, but hey...
  82436. i.object.rotationQuaternion = oldQuaternion;
  82437. });
  82438. impostor.physicsBody = this.world.add(bodyConfig);
  82439. }
  82440. else {
  82441. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  82442. }
  82443. impostor.setDeltaPosition(this._tmpPositionVector);
  82444. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  82445. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  82446. };
  82447. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82448. //impostor.physicsBody.dispose();
  82449. //Same as : (older oimo versions)
  82450. this.world.removeRigidBody(impostor.physicsBody);
  82451. };
  82452. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82453. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82454. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82455. if (!mainBody || !connectedBody) {
  82456. return;
  82457. }
  82458. var jointData = impostorJoint.joint.jointData;
  82459. var options = jointData.nativeParams || {};
  82460. var type;
  82461. var nativeJointData = {
  82462. body1: mainBody,
  82463. body2: connectedBody,
  82464. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  82465. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  82466. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  82467. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  82468. min: options.min,
  82469. max: options.max,
  82470. collision: options.collision || jointData.collision,
  82471. spring: options.spring,
  82472. //supporting older version of Oimo
  82473. world: this.world
  82474. };
  82475. switch (impostorJoint.joint.type) {
  82476. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82477. type = "jointBall";
  82478. break;
  82479. case BABYLON.PhysicsJoint.SpringJoint:
  82480. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  82481. var springData = jointData;
  82482. nativeJointData.min = springData.length || nativeJointData.min;
  82483. //Max should also be set, just make sure it is at least min
  82484. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  82485. case BABYLON.PhysicsJoint.DistanceJoint:
  82486. type = "jointDistance";
  82487. nativeJointData.max = jointData.maxDistance;
  82488. break;
  82489. case BABYLON.PhysicsJoint.PrismaticJoint:
  82490. type = "jointPrisme";
  82491. break;
  82492. case BABYLON.PhysicsJoint.SliderJoint:
  82493. type = "jointSlide";
  82494. break;
  82495. case BABYLON.PhysicsJoint.WheelJoint:
  82496. type = "jointWheel";
  82497. break;
  82498. case BABYLON.PhysicsJoint.HingeJoint:
  82499. default:
  82500. type = "jointHinge";
  82501. break;
  82502. }
  82503. nativeJointData.type = type;
  82504. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82505. };
  82506. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82507. //Bug in Oimo prevents us from disposing a joint in the playground
  82508. //joint.joint.physicsJoint.dispose();
  82509. //So we will bruteforce it!
  82510. try {
  82511. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82512. }
  82513. catch (e) {
  82514. BABYLON.Tools.Warn(e);
  82515. }
  82516. };
  82517. OimoJSPlugin.prototype.isSupported = function () {
  82518. return this.BJSOIMO !== undefined;
  82519. };
  82520. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82521. if (!impostor.physicsBody.sleeping) {
  82522. //TODO check that
  82523. /*if (impostor.physicsBody.shapes.next) {
  82524. var parentShape = this._getLastShape(impostor.physicsBody);
  82525. impostor.object.position.copyFrom(parentShape.position);
  82526. console.log(parentShape.position);
  82527. } else {*/
  82528. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82529. //}
  82530. if (impostor.object.rotationQuaternion) {
  82531. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82532. }
  82533. }
  82534. };
  82535. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82536. var body = impostor.physicsBody;
  82537. body.position.copy(newPosition);
  82538. body.orientation.copy(newRotation);
  82539. body.syncShapes();
  82540. body.awake();
  82541. };
  82542. /*private _getLastShape(body: any): any {
  82543. var lastShape = body.shapes;
  82544. while (lastShape.next) {
  82545. lastShape = lastShape.next;
  82546. }
  82547. return lastShape;
  82548. }*/
  82549. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82550. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82551. };
  82552. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82553. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82554. };
  82555. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82556. var v = impostor.physicsBody.linearVelocity;
  82557. if (!v) {
  82558. return null;
  82559. }
  82560. return new BABYLON.Vector3(v.x, v.y, v.z);
  82561. };
  82562. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82563. var v = impostor.physicsBody.angularVelocity;
  82564. if (!v) {
  82565. return null;
  82566. }
  82567. return new BABYLON.Vector3(v.x, v.y, v.z);
  82568. };
  82569. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82570. var staticBody = mass === 0;
  82571. //this will actually set the body's density and not its mass.
  82572. //But this is how oimo treats the mass variable.
  82573. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82574. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82575. };
  82576. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82577. return impostor.physicsBody.shapes.density;
  82578. };
  82579. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82580. return impostor.physicsBody.shapes.friction;
  82581. };
  82582. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82583. impostor.physicsBody.shapes.friction = friction;
  82584. };
  82585. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82586. return impostor.physicsBody.shapes.restitution;
  82587. };
  82588. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82589. impostor.physicsBody.shapes.restitution = restitution;
  82590. };
  82591. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82592. impostor.physicsBody.sleep();
  82593. };
  82594. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82595. impostor.physicsBody.awake();
  82596. };
  82597. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82598. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82599. if (minDistance !== void 0) {
  82600. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82601. }
  82602. };
  82603. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82604. //TODO separate rotational and transational motors.
  82605. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82606. if (motor) {
  82607. motor.setMotor(speed, maxForce);
  82608. }
  82609. };
  82610. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82611. //TODO separate rotational and transational motors.
  82612. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82613. if (motor) {
  82614. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82615. }
  82616. };
  82617. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82618. var body = impostor.physicsBody;
  82619. mesh.position.x = body.position.x;
  82620. mesh.position.y = body.position.y;
  82621. mesh.position.z = body.position.z;
  82622. if (mesh.rotationQuaternion) {
  82623. mesh.rotationQuaternion.x = body.orientation.x;
  82624. mesh.rotationQuaternion.y = body.orientation.y;
  82625. mesh.rotationQuaternion.z = body.orientation.z;
  82626. mesh.rotationQuaternion.w = body.orientation.s;
  82627. }
  82628. };
  82629. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82630. return impostor.physicsBody.shapes.radius;
  82631. };
  82632. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82633. var shape = impostor.physicsBody.shapes;
  82634. result.x = shape.halfWidth * 2;
  82635. result.y = shape.halfHeight * 2;
  82636. result.z = shape.halfDepth * 2;
  82637. };
  82638. OimoJSPlugin.prototype.dispose = function () {
  82639. this.world.clear();
  82640. };
  82641. return OimoJSPlugin;
  82642. }());
  82643. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82644. })(BABYLON || (BABYLON = {}));
  82645. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82646. var BABYLON;
  82647. (function (BABYLON) {
  82648. /*
  82649. * Based on jsTGALoader - Javascript loader for TGA file
  82650. * By Vincent Thibault
  82651. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82652. */
  82653. var TGATools = /** @class */ (function () {
  82654. function TGATools() {
  82655. }
  82656. TGATools.GetTGAHeader = function (data) {
  82657. var offset = 0;
  82658. var header = {
  82659. id_length: data[offset++],
  82660. colormap_type: data[offset++],
  82661. image_type: data[offset++],
  82662. colormap_index: data[offset++] | data[offset++] << 8,
  82663. colormap_length: data[offset++] | data[offset++] << 8,
  82664. colormap_size: data[offset++],
  82665. origin: [
  82666. data[offset++] | data[offset++] << 8,
  82667. data[offset++] | data[offset++] << 8
  82668. ],
  82669. width: data[offset++] | data[offset++] << 8,
  82670. height: data[offset++] | data[offset++] << 8,
  82671. pixel_size: data[offset++],
  82672. flags: data[offset++]
  82673. };
  82674. return header;
  82675. };
  82676. TGATools.UploadContent = function (gl, data) {
  82677. // Not enough data to contain header ?
  82678. if (data.length < 19) {
  82679. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82680. return;
  82681. }
  82682. // Read Header
  82683. var offset = 18;
  82684. var header = TGATools.GetTGAHeader(data);
  82685. // Assume it's a valid Targa file.
  82686. if (header.id_length + offset > data.length) {
  82687. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82688. return;
  82689. }
  82690. // Skip not needed data
  82691. offset += header.id_length;
  82692. var use_rle = false;
  82693. var use_pal = false;
  82694. var use_grey = false;
  82695. // Get some informations.
  82696. switch (header.image_type) {
  82697. case TGATools._TYPE_RLE_INDEXED:
  82698. use_rle = true;
  82699. case TGATools._TYPE_INDEXED:
  82700. use_pal = true;
  82701. break;
  82702. case TGATools._TYPE_RLE_RGB:
  82703. use_rle = true;
  82704. case TGATools._TYPE_RGB:
  82705. // use_rgb = true;
  82706. break;
  82707. case TGATools._TYPE_RLE_GREY:
  82708. use_rle = true;
  82709. case TGATools._TYPE_GREY:
  82710. use_grey = true;
  82711. break;
  82712. }
  82713. var pixel_data;
  82714. // var numAlphaBits = header.flags & 0xf;
  82715. var pixel_size = header.pixel_size >> 3;
  82716. var pixel_total = header.width * header.height * pixel_size;
  82717. // Read palettes
  82718. var palettes;
  82719. if (use_pal) {
  82720. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82721. }
  82722. // Read LRE
  82723. if (use_rle) {
  82724. pixel_data = new Uint8Array(pixel_total);
  82725. var c, count, i;
  82726. var localOffset = 0;
  82727. var pixels = new Uint8Array(pixel_size);
  82728. while (offset < pixel_total && localOffset < pixel_total) {
  82729. c = data[offset++];
  82730. count = (c & 0x7f) + 1;
  82731. // RLE pixels
  82732. if (c & 0x80) {
  82733. // Bind pixel tmp array
  82734. for (i = 0; i < pixel_size; ++i) {
  82735. pixels[i] = data[offset++];
  82736. }
  82737. // Copy pixel array
  82738. for (i = 0; i < count; ++i) {
  82739. pixel_data.set(pixels, localOffset + i * pixel_size);
  82740. }
  82741. localOffset += pixel_size * count;
  82742. }
  82743. // Raw pixels
  82744. else {
  82745. count *= pixel_size;
  82746. for (i = 0; i < count; ++i) {
  82747. pixel_data[localOffset + i] = data[offset++];
  82748. }
  82749. localOffset += count;
  82750. }
  82751. }
  82752. }
  82753. // RAW Pixels
  82754. else {
  82755. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82756. }
  82757. // Load to texture
  82758. var x_start, y_start, x_step, y_step, y_end, x_end;
  82759. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82760. default:
  82761. case TGATools._ORIGIN_UL:
  82762. x_start = 0;
  82763. x_step = 1;
  82764. x_end = header.width;
  82765. y_start = 0;
  82766. y_step = 1;
  82767. y_end = header.height;
  82768. break;
  82769. case TGATools._ORIGIN_BL:
  82770. x_start = 0;
  82771. x_step = 1;
  82772. x_end = header.width;
  82773. y_start = header.height - 1;
  82774. y_step = -1;
  82775. y_end = -1;
  82776. break;
  82777. case TGATools._ORIGIN_UR:
  82778. x_start = header.width - 1;
  82779. x_step = -1;
  82780. x_end = -1;
  82781. y_start = 0;
  82782. y_step = 1;
  82783. y_end = header.height;
  82784. break;
  82785. case TGATools._ORIGIN_BR:
  82786. x_start = header.width - 1;
  82787. x_step = -1;
  82788. x_end = -1;
  82789. y_start = header.height - 1;
  82790. y_step = -1;
  82791. y_end = -1;
  82792. break;
  82793. }
  82794. // Load the specify method
  82795. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82796. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82797. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82798. };
  82799. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82800. var image = pixel_data, colormap = palettes;
  82801. var width = header.width, height = header.height;
  82802. var color, i = 0, x, y;
  82803. var imageData = new Uint8Array(width * height * 4);
  82804. for (y = y_start; y !== y_end; y += y_step) {
  82805. for (x = x_start; x !== x_end; x += x_step, i++) {
  82806. color = image[i];
  82807. imageData[(x + width * y) * 4 + 3] = 255;
  82808. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82809. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82810. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82811. }
  82812. }
  82813. return imageData;
  82814. };
  82815. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82816. var image = pixel_data;
  82817. var width = header.width, height = header.height;
  82818. var color, i = 0, x, y;
  82819. var imageData = new Uint8Array(width * height * 4);
  82820. for (y = y_start; y !== y_end; y += y_step) {
  82821. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82822. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82823. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82824. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82825. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82826. imageData[(x + width * y) * 4 + 0] = r;
  82827. imageData[(x + width * y) * 4 + 1] = g;
  82828. imageData[(x + width * y) * 4 + 2] = b;
  82829. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82830. }
  82831. }
  82832. return imageData;
  82833. };
  82834. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82835. var image = pixel_data;
  82836. var width = header.width, height = header.height;
  82837. var i = 0, x, y;
  82838. var imageData = new Uint8Array(width * height * 4);
  82839. for (y = y_start; y !== y_end; y += y_step) {
  82840. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82841. imageData[(x + width * y) * 4 + 3] = 255;
  82842. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82843. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82844. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82845. }
  82846. }
  82847. return imageData;
  82848. };
  82849. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82850. var image = pixel_data;
  82851. var width = header.width, height = header.height;
  82852. var i = 0, x, y;
  82853. var imageData = new Uint8Array(width * height * 4);
  82854. for (y = y_start; y !== y_end; y += y_step) {
  82855. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82856. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82857. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82858. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82859. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82860. }
  82861. }
  82862. return imageData;
  82863. };
  82864. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82865. var image = pixel_data;
  82866. var width = header.width, height = header.height;
  82867. var color, i = 0, x, y;
  82868. var imageData = new Uint8Array(width * height * 4);
  82869. for (y = y_start; y !== y_end; y += y_step) {
  82870. for (x = x_start; x !== x_end; x += x_step, i++) {
  82871. color = image[i];
  82872. imageData[(x + width * y) * 4 + 0] = color;
  82873. imageData[(x + width * y) * 4 + 1] = color;
  82874. imageData[(x + width * y) * 4 + 2] = color;
  82875. imageData[(x + width * y) * 4 + 3] = 255;
  82876. }
  82877. }
  82878. return imageData;
  82879. };
  82880. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82881. var image = pixel_data;
  82882. var width = header.width, height = header.height;
  82883. var i = 0, x, y;
  82884. var imageData = new Uint8Array(width * height * 4);
  82885. for (y = y_start; y !== y_end; y += y_step) {
  82886. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82887. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82888. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82889. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82890. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82891. }
  82892. }
  82893. return imageData;
  82894. };
  82895. //private static _TYPE_NO_DATA = 0;
  82896. TGATools._TYPE_INDEXED = 1;
  82897. TGATools._TYPE_RGB = 2;
  82898. TGATools._TYPE_GREY = 3;
  82899. TGATools._TYPE_RLE_INDEXED = 9;
  82900. TGATools._TYPE_RLE_RGB = 10;
  82901. TGATools._TYPE_RLE_GREY = 11;
  82902. TGATools._ORIGIN_MASK = 0x30;
  82903. TGATools._ORIGIN_SHIFT = 0x04;
  82904. TGATools._ORIGIN_BL = 0x00;
  82905. TGATools._ORIGIN_BR = 0x01;
  82906. TGATools._ORIGIN_UL = 0x02;
  82907. TGATools._ORIGIN_UR = 0x03;
  82908. return TGATools;
  82909. }());
  82910. BABYLON.TGATools = TGATools;
  82911. })(BABYLON || (BABYLON = {}));
  82912. //# sourceMappingURL=babylon.tga.js.map
  82913. var BABYLON;
  82914. (function (BABYLON) {
  82915. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  82916. // All values and structures referenced from:
  82917. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  82918. var DDS_MAGIC = 0x20534444;
  82919. var
  82920. //DDSD_CAPS = 0x1,
  82921. //DDSD_HEIGHT = 0x2,
  82922. //DDSD_WIDTH = 0x4,
  82923. //DDSD_PITCH = 0x8,
  82924. //DDSD_PIXELFORMAT = 0x1000,
  82925. DDSD_MIPMAPCOUNT = 0x20000;
  82926. //DDSD_LINEARSIZE = 0x80000,
  82927. //DDSD_DEPTH = 0x800000;
  82928. // var DDSCAPS_COMPLEX = 0x8,
  82929. // DDSCAPS_MIPMAP = 0x400000,
  82930. // DDSCAPS_TEXTURE = 0x1000;
  82931. var DDSCAPS2_CUBEMAP = 0x200;
  82932. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82933. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82934. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82935. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82936. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82937. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82938. // DDSCAPS2_VOLUME = 0x200000;
  82939. var
  82940. //DDPF_ALPHAPIXELS = 0x1,
  82941. //DDPF_ALPHA = 0x2,
  82942. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82943. //DDPF_YUV = 0x200,
  82944. DDPF_LUMINANCE = 0x20000;
  82945. function FourCCToInt32(value) {
  82946. return value.charCodeAt(0) +
  82947. (value.charCodeAt(1) << 8) +
  82948. (value.charCodeAt(2) << 16) +
  82949. (value.charCodeAt(3) << 24);
  82950. }
  82951. function Int32ToFourCC(value) {
  82952. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82953. }
  82954. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82955. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82956. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82957. var FOURCC_DX10 = FourCCToInt32("DX10");
  82958. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82959. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82960. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82961. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82962. var headerLengthInt = 31; // The header length in 32 bit ints
  82963. // Offsets into the header array
  82964. var off_magic = 0;
  82965. var off_size = 1;
  82966. var off_flags = 2;
  82967. var off_height = 3;
  82968. var off_width = 4;
  82969. var off_mipmapCount = 7;
  82970. var off_pfFlags = 20;
  82971. var off_pfFourCC = 21;
  82972. var off_RGBbpp = 22;
  82973. var off_RMask = 23;
  82974. var off_GMask = 24;
  82975. var off_BMask = 25;
  82976. var off_AMask = 26;
  82977. // var off_caps1 = 27;
  82978. var off_caps2 = 28;
  82979. // var off_caps3 = 29;
  82980. // var off_caps4 = 30;
  82981. var off_dxgiFormat = 32;
  82982. ;
  82983. var DDSTools = /** @class */ (function () {
  82984. function DDSTools() {
  82985. }
  82986. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82987. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82988. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82989. var mipmapCount = 1;
  82990. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82991. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82992. }
  82993. var fourCC = header[off_pfFourCC];
  82994. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82995. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82996. switch (fourCC) {
  82997. case FOURCC_D3DFMT_R16G16B16A16F:
  82998. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82999. break;
  83000. case FOURCC_D3DFMT_R32G32B32A32F:
  83001. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83002. break;
  83003. case FOURCC_DX10:
  83004. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83005. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83006. break;
  83007. }
  83008. }
  83009. return {
  83010. width: header[off_width],
  83011. height: header[off_height],
  83012. mipmapCount: mipmapCount,
  83013. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83014. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83015. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83016. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83017. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83018. dxgiFormat: dxgiFormat,
  83019. textureType: textureType
  83020. };
  83021. };
  83022. DDSTools._ToHalfFloat = function (value) {
  83023. if (!DDSTools._FloatView) {
  83024. DDSTools._FloatView = new Float32Array(1);
  83025. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83026. }
  83027. DDSTools._FloatView[0] = value;
  83028. var x = DDSTools._Int32View[0];
  83029. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83030. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83031. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83032. /* If zero, or denormal, or exponent underflows too much for a denormal
  83033. * half, return signed zero. */
  83034. if (e < 103) {
  83035. return bits;
  83036. }
  83037. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83038. if (e > 142) {
  83039. bits |= 0x7c00;
  83040. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83041. * not Inf, so make sure we set one mantissa bit too. */
  83042. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83043. return bits;
  83044. }
  83045. /* If exponent underflows but not too much, return a denormal */
  83046. if (e < 113) {
  83047. m |= 0x0800;
  83048. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83049. * to 1, which is OK. */
  83050. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83051. return bits;
  83052. }
  83053. bits |= ((e - 112) << 10) | (m >> 1);
  83054. bits += m & 1;
  83055. return bits;
  83056. };
  83057. DDSTools._FromHalfFloat = function (value) {
  83058. var s = (value & 0x8000) >> 15;
  83059. var e = (value & 0x7C00) >> 10;
  83060. var f = value & 0x03FF;
  83061. if (e === 0) {
  83062. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83063. }
  83064. else if (e == 0x1F) {
  83065. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83066. }
  83067. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83068. };
  83069. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83070. var destArray = new Float32Array(dataLength);
  83071. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83072. var index = 0;
  83073. for (var y = 0; y < height; y++) {
  83074. for (var x = 0; x < width; x++) {
  83075. var srcPos = (x + y * width) * 4;
  83076. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83077. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83078. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83079. if (DDSTools.StoreLODInAlphaChannel) {
  83080. destArray[index + 3] = lod;
  83081. }
  83082. else {
  83083. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83084. }
  83085. index += 4;
  83086. }
  83087. }
  83088. return destArray;
  83089. };
  83090. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83091. if (DDSTools.StoreLODInAlphaChannel) {
  83092. var destArray = new Uint16Array(dataLength);
  83093. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83094. var index = 0;
  83095. for (var y = 0; y < height; y++) {
  83096. for (var x = 0; x < width; x++) {
  83097. var srcPos = (x + y * width) * 4;
  83098. destArray[index] = srcData[srcPos];
  83099. destArray[index + 1] = srcData[srcPos + 1];
  83100. destArray[index + 2] = srcData[srcPos + 2];
  83101. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83102. index += 4;
  83103. }
  83104. }
  83105. return destArray;
  83106. }
  83107. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83108. };
  83109. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83110. if (DDSTools.StoreLODInAlphaChannel) {
  83111. var destArray = new Float32Array(dataLength);
  83112. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83113. var index = 0;
  83114. for (var y = 0; y < height; y++) {
  83115. for (var x = 0; x < width; x++) {
  83116. var srcPos = (x + y * width) * 4;
  83117. destArray[index] = srcData[srcPos];
  83118. destArray[index + 1] = srcData[srcPos + 1];
  83119. destArray[index + 2] = srcData[srcPos + 2];
  83120. destArray[index + 3] = lod;
  83121. index += 4;
  83122. }
  83123. }
  83124. return destArray;
  83125. }
  83126. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83127. };
  83128. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83129. var destArray = new Uint8Array(dataLength);
  83130. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83131. var index = 0;
  83132. for (var y = 0; y < height; y++) {
  83133. for (var x = 0; x < width; x++) {
  83134. var srcPos = (x + y * width) * 4;
  83135. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83136. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83137. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83138. if (DDSTools.StoreLODInAlphaChannel) {
  83139. destArray[index + 3] = lod;
  83140. }
  83141. else {
  83142. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83143. }
  83144. index += 4;
  83145. }
  83146. }
  83147. return destArray;
  83148. };
  83149. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83150. var destArray = new Uint8Array(dataLength);
  83151. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83152. var index = 0;
  83153. for (var y = 0; y < height; y++) {
  83154. for (var x = 0; x < width; x++) {
  83155. var srcPos = (x + y * width) * 4;
  83156. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83157. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83158. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83159. if (DDSTools.StoreLODInAlphaChannel) {
  83160. destArray[index + 3] = lod;
  83161. }
  83162. else {
  83163. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83164. }
  83165. index += 4;
  83166. }
  83167. }
  83168. return destArray;
  83169. };
  83170. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83171. var byteArray = new Uint8Array(dataLength);
  83172. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83173. var index = 0;
  83174. for (var y = 0; y < height; y++) {
  83175. for (var x = 0; x < width; x++) {
  83176. var srcPos = (x + y * width) * 4;
  83177. byteArray[index] = srcData[srcPos + rOffset];
  83178. byteArray[index + 1] = srcData[srcPos + gOffset];
  83179. byteArray[index + 2] = srcData[srcPos + bOffset];
  83180. byteArray[index + 3] = srcData[srcPos + aOffset];
  83181. index += 4;
  83182. }
  83183. }
  83184. return byteArray;
  83185. };
  83186. DDSTools._ExtractLongWordOrder = function (value) {
  83187. if (value === 0 || value === 255 || value === -16777216) {
  83188. return 0;
  83189. }
  83190. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83191. };
  83192. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83193. var byteArray = new Uint8Array(dataLength);
  83194. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83195. var index = 0;
  83196. for (var y = 0; y < height; y++) {
  83197. for (var x = 0; x < width; x++) {
  83198. var srcPos = (x + y * width) * 3;
  83199. byteArray[index] = srcData[srcPos + rOffset];
  83200. byteArray[index + 1] = srcData[srcPos + gOffset];
  83201. byteArray[index + 2] = srcData[srcPos + bOffset];
  83202. index += 3;
  83203. }
  83204. }
  83205. return byteArray;
  83206. };
  83207. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83208. var byteArray = new Uint8Array(dataLength);
  83209. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83210. var index = 0;
  83211. for (var y = 0; y < height; y++) {
  83212. for (var x = 0; x < width; x++) {
  83213. var srcPos = (x + y * width);
  83214. byteArray[index] = srcData[srcPos];
  83215. index++;
  83216. }
  83217. }
  83218. return byteArray;
  83219. };
  83220. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83221. if (lodIndex === void 0) { lodIndex = -1; }
  83222. var ext = engine.getCaps().s3tc;
  83223. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83224. var fourCC, width, height, dataLength = 0, dataOffset;
  83225. var byteArray, mipmapCount, mip;
  83226. var internalFormat = 0;
  83227. var format = 0;
  83228. var blockBytes = 1;
  83229. if (header[off_magic] !== DDS_MAGIC) {
  83230. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83231. return;
  83232. }
  83233. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83234. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83235. return;
  83236. }
  83237. if (info.isCompressed && !ext) {
  83238. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83239. return;
  83240. }
  83241. var bpp = header[off_RGBbpp];
  83242. dataOffset = header[off_size] + 4;
  83243. var computeFormats = false;
  83244. if (info.isFourCC) {
  83245. fourCC = header[off_pfFourCC];
  83246. switch (fourCC) {
  83247. case FOURCC_DXT1:
  83248. blockBytes = 8;
  83249. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83250. break;
  83251. case FOURCC_DXT3:
  83252. blockBytes = 16;
  83253. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83254. break;
  83255. case FOURCC_DXT5:
  83256. blockBytes = 16;
  83257. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83258. break;
  83259. case FOURCC_D3DFMT_R16G16B16A16F:
  83260. computeFormats = true;
  83261. break;
  83262. case FOURCC_D3DFMT_R32G32B32A32F:
  83263. computeFormats = true;
  83264. break;
  83265. case FOURCC_DX10:
  83266. // There is an additionnal header so dataOffset need to be changed
  83267. dataOffset += 5 * 4; // 5 uints
  83268. var supported = false;
  83269. switch (info.dxgiFormat) {
  83270. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83271. computeFormats = true;
  83272. supported = true;
  83273. break;
  83274. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83275. info.isRGB = true;
  83276. info.isFourCC = false;
  83277. bpp = 32;
  83278. supported = true;
  83279. break;
  83280. }
  83281. if (supported) {
  83282. break;
  83283. }
  83284. default:
  83285. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83286. return;
  83287. }
  83288. }
  83289. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83290. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83291. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83292. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83293. if (computeFormats) {
  83294. format = engine._getWebGLTextureType(info.textureType);
  83295. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83296. }
  83297. mipmapCount = 1;
  83298. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83299. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83300. }
  83301. for (var face = 0; face < faces; face++) {
  83302. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83303. width = header[off_width];
  83304. height = header[off_height];
  83305. for (mip = 0; mip < mipmapCount; ++mip) {
  83306. if (lodIndex === -1 || lodIndex === mip) {
  83307. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83308. var i = (lodIndex === -1) ? mip : 0;
  83309. if (!info.isCompressed && info.isFourCC) {
  83310. dataLength = width * height * 4;
  83311. var floatArray = null;
  83312. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  83313. if (bpp === 128) {
  83314. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83315. }
  83316. else if (bpp === 64) {
  83317. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83318. }
  83319. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83320. format = engine._getWebGLTextureType(info.textureType);
  83321. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83322. }
  83323. else {
  83324. if (bpp === 128) {
  83325. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83326. }
  83327. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  83328. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83329. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83330. format = engine._getWebGLTextureType(info.textureType);
  83331. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83332. }
  83333. else { // 64
  83334. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83335. }
  83336. }
  83337. if (floatArray) {
  83338. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  83339. }
  83340. }
  83341. else if (info.isRGB) {
  83342. if (bpp === 24) {
  83343. dataLength = width * height * 3;
  83344. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  83345. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  83346. }
  83347. else { // 32
  83348. dataLength = width * height * 4;
  83349. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  83350. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  83351. }
  83352. }
  83353. else if (info.isLuminance) {
  83354. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  83355. var unpaddedRowSize = width;
  83356. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  83357. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  83358. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  83359. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  83360. }
  83361. else {
  83362. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  83363. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  83364. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  83365. }
  83366. }
  83367. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  83368. width *= 0.5;
  83369. height *= 0.5;
  83370. width = Math.max(1.0, width);
  83371. height = Math.max(1.0, height);
  83372. }
  83373. if (currentFace !== undefined) {
  83374. // Loading a single face
  83375. break;
  83376. }
  83377. }
  83378. };
  83379. DDSTools.StoreLODInAlphaChannel = false;
  83380. return DDSTools;
  83381. }());
  83382. BABYLON.DDSTools = DDSTools;
  83383. })(BABYLON || (BABYLON = {}));
  83384. //# sourceMappingURL=babylon.dds.js.map
  83385. var BABYLON;
  83386. (function (BABYLON) {
  83387. /**
  83388. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  83389. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  83390. */
  83391. var KhronosTextureContainer = /** @class */ (function () {
  83392. /**
  83393. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  83394. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  83395. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  83396. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  83397. */
  83398. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  83399. this.arrayBuffer = arrayBuffer;
  83400. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  83401. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  83402. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  83403. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  83404. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  83405. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  83406. BABYLON.Tools.Error("texture missing KTX identifier");
  83407. return;
  83408. }
  83409. // load the reset of the header in native 32 bit int
  83410. var header = new Int32Array(this.arrayBuffer, 12, 13);
  83411. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  83412. var oppositeEndianess = header[0] === 0x01020304;
  83413. // read all the header elements in order they exist in the file, without modification (sans endainness)
  83414. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  83415. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  83416. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  83417. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  83418. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  83419. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  83420. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  83421. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  83422. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  83423. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  83424. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  83425. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  83426. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  83427. if (this.glType !== 0) {
  83428. BABYLON.Tools.Error("only compressed formats currently supported");
  83429. return;
  83430. }
  83431. else {
  83432. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  83433. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  83434. }
  83435. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  83436. BABYLON.Tools.Error("only 2D textures currently supported");
  83437. return;
  83438. }
  83439. if (this.numberOfArrayElements !== 0) {
  83440. BABYLON.Tools.Error("texture arrays not currently supported");
  83441. return;
  83442. }
  83443. if (this.numberOfFaces !== facesExpected) {
  83444. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  83445. return;
  83446. }
  83447. // we now have a completely validated file, so could use existence of loadType as success
  83448. // would need to make this more elaborate & adjust checks above to support more than one load type
  83449. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  83450. }
  83451. // not as fast hardware based, but will probably never need to use
  83452. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  83453. return ((val & 0xFF) << 24)
  83454. | ((val & 0xFF00) << 8)
  83455. | ((val >> 8) & 0xFF00)
  83456. | ((val >> 24) & 0xFF);
  83457. };
  83458. /**
  83459. * It is assumed that the texture has already been created & is currently bound
  83460. */
  83461. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  83462. switch (this.loadType) {
  83463. case KhronosTextureContainer.COMPRESSED_2D:
  83464. this._upload2DCompressedLevels(gl, loadMipmaps);
  83465. break;
  83466. case KhronosTextureContainer.TEX_2D:
  83467. case KhronosTextureContainer.COMPRESSED_3D:
  83468. case KhronosTextureContainer.TEX_3D:
  83469. }
  83470. };
  83471. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  83472. // initialize width & height for level 1
  83473. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  83474. var width = this.pixelWidth;
  83475. var height = this.pixelHeight;
  83476. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  83477. for (var level = 0; level < mipmapCount; level++) {
  83478. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  83479. for (var face = 0; face < this.numberOfFaces; face++) {
  83480. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  83481. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  83482. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  83483. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  83484. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  83485. }
  83486. width = Math.max(1.0, width * 0.5);
  83487. height = Math.max(1.0, height * 0.5);
  83488. }
  83489. };
  83490. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83491. // load types
  83492. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83493. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83494. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83495. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83496. return KhronosTextureContainer;
  83497. }());
  83498. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83499. })(BABYLON || (BABYLON = {}));
  83500. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83501. var BABYLON;
  83502. (function (BABYLON) {
  83503. var Debug;
  83504. (function (Debug) {
  83505. /**
  83506. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83507. */
  83508. var SkeletonViewer = /** @class */ (function () {
  83509. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83510. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83511. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83512. this.skeleton = skeleton;
  83513. this.mesh = mesh;
  83514. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83515. this.renderingGroupId = renderingGroupId;
  83516. this.color = BABYLON.Color3.White();
  83517. this._debugLines = new Array();
  83518. this._isEnabled = false;
  83519. this._scene = scene;
  83520. this.update();
  83521. this._renderFunction = this.update.bind(this);
  83522. }
  83523. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83524. get: function () {
  83525. return this._isEnabled;
  83526. },
  83527. set: function (value) {
  83528. if (this._isEnabled === value) {
  83529. return;
  83530. }
  83531. this._isEnabled = value;
  83532. if (value) {
  83533. this._scene.registerBeforeRender(this._renderFunction);
  83534. }
  83535. else {
  83536. this._scene.unregisterBeforeRender(this._renderFunction);
  83537. }
  83538. },
  83539. enumerable: true,
  83540. configurable: true
  83541. });
  83542. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83543. if (x === void 0) { x = 0; }
  83544. if (y === void 0) { y = 0; }
  83545. if (z === void 0) { z = 0; }
  83546. var tmat = BABYLON.Tmp.Matrix[0];
  83547. var parentBone = bone.getParent();
  83548. tmat.copyFrom(bone.getLocalMatrix());
  83549. if (x !== 0 || y !== 0 || z !== 0) {
  83550. var tmat2 = BABYLON.Tmp.Matrix[1];
  83551. BABYLON.Matrix.IdentityToRef(tmat2);
  83552. tmat2.m[12] = x;
  83553. tmat2.m[13] = y;
  83554. tmat2.m[14] = z;
  83555. tmat2.multiplyToRef(tmat, tmat);
  83556. }
  83557. if (parentBone) {
  83558. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83559. }
  83560. tmat.multiplyToRef(meshMat, tmat);
  83561. position.x = tmat.m[12];
  83562. position.y = tmat.m[13];
  83563. position.z = tmat.m[14];
  83564. };
  83565. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83566. var len = bones.length;
  83567. var meshPos = this.mesh.position;
  83568. for (var i = 0; i < len; i++) {
  83569. var bone = bones[i];
  83570. var points = this._debugLines[i];
  83571. if (!points) {
  83572. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83573. this._debugLines[i] = points;
  83574. }
  83575. this._getBonePosition(points[0], bone, meshMat);
  83576. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83577. points[0].subtractInPlace(meshPos);
  83578. points[1].subtractInPlace(meshPos);
  83579. }
  83580. };
  83581. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83582. var len = bones.length;
  83583. var boneNum = 0;
  83584. var meshPos = this.mesh.position;
  83585. for (var i = len - 1; i >= 0; i--) {
  83586. var childBone = bones[i];
  83587. var parentBone = childBone.getParent();
  83588. if (!parentBone) {
  83589. continue;
  83590. }
  83591. var points = this._debugLines[boneNum];
  83592. if (!points) {
  83593. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83594. this._debugLines[boneNum] = points;
  83595. }
  83596. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83597. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83598. points[0].subtractInPlace(meshPos);
  83599. points[1].subtractInPlace(meshPos);
  83600. boneNum++;
  83601. }
  83602. };
  83603. SkeletonViewer.prototype.update = function () {
  83604. if (this.autoUpdateBonesMatrices) {
  83605. this.skeleton.computeAbsoluteTransforms();
  83606. }
  83607. if (this.skeleton.bones[0].length === undefined) {
  83608. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83609. }
  83610. else {
  83611. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83612. }
  83613. if (!this._debugMesh) {
  83614. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83615. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83616. }
  83617. else {
  83618. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83619. }
  83620. this._debugMesh.position.copyFrom(this.mesh.position);
  83621. this._debugMesh.color = this.color;
  83622. };
  83623. SkeletonViewer.prototype.dispose = function () {
  83624. if (this._debugMesh) {
  83625. this.isEnabled = false;
  83626. this._debugMesh.dispose();
  83627. this._debugMesh = null;
  83628. }
  83629. };
  83630. return SkeletonViewer;
  83631. }());
  83632. Debug.SkeletonViewer = SkeletonViewer;
  83633. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83634. })(BABYLON || (BABYLON = {}));
  83635. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83636. /**
  83637. * Module Debug contains the (visual) components to debug a scene correctly
  83638. */
  83639. var BABYLON;
  83640. (function (BABYLON) {
  83641. var Debug;
  83642. (function (Debug) {
  83643. /**
  83644. * The Axes viewer will show 3 axes in a specific point in space
  83645. */
  83646. var AxesViewer = /** @class */ (function () {
  83647. function AxesViewer(scene, scaleLines) {
  83648. if (scaleLines === void 0) { scaleLines = 1; }
  83649. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83650. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83651. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83652. this.scaleLines = 1;
  83653. this.scaleLines = scaleLines;
  83654. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83655. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83656. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83657. this._xmesh.renderingGroupId = 2;
  83658. this._ymesh.renderingGroupId = 2;
  83659. this._zmesh.renderingGroupId = 2;
  83660. this._xmesh.material.checkReadyOnlyOnce = true;
  83661. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83662. this._ymesh.material.checkReadyOnlyOnce = true;
  83663. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83664. this._zmesh.material.checkReadyOnlyOnce = true;
  83665. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83666. this.scene = scene;
  83667. }
  83668. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83669. var scaleLines = this.scaleLines;
  83670. if (this._xmesh) {
  83671. this._xmesh.position.copyFrom(position);
  83672. }
  83673. if (this._ymesh) {
  83674. this._ymesh.position.copyFrom(position);
  83675. }
  83676. if (this._zmesh) {
  83677. this._zmesh.position.copyFrom(position);
  83678. }
  83679. var point2 = this._xline[1];
  83680. point2.x = xaxis.x * scaleLines;
  83681. point2.y = xaxis.y * scaleLines;
  83682. point2.z = xaxis.z * scaleLines;
  83683. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83684. point2 = this._yline[1];
  83685. point2.x = yaxis.x * scaleLines;
  83686. point2.y = yaxis.y * scaleLines;
  83687. point2.z = yaxis.z * scaleLines;
  83688. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83689. point2 = this._zline[1];
  83690. point2.x = zaxis.x * scaleLines;
  83691. point2.y = zaxis.y * scaleLines;
  83692. point2.z = zaxis.z * scaleLines;
  83693. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83694. };
  83695. AxesViewer.prototype.dispose = function () {
  83696. if (this._xmesh) {
  83697. this._xmesh.dispose();
  83698. }
  83699. if (this._ymesh) {
  83700. this._ymesh.dispose();
  83701. }
  83702. if (this._zmesh) {
  83703. this._zmesh.dispose();
  83704. }
  83705. this._xmesh = null;
  83706. this._ymesh = null;
  83707. this._zmesh = null;
  83708. this.scene = null;
  83709. };
  83710. return AxesViewer;
  83711. }());
  83712. Debug.AxesViewer = AxesViewer;
  83713. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83714. })(BABYLON || (BABYLON = {}));
  83715. //# sourceMappingURL=babylon.axesViewer.js.map
  83716. var BABYLON;
  83717. (function (BABYLON) {
  83718. var Debug;
  83719. (function (Debug) {
  83720. /**
  83721. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83722. */
  83723. var BoneAxesViewer = /** @class */ (function (_super) {
  83724. __extends(BoneAxesViewer, _super);
  83725. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83726. if (scaleLines === void 0) { scaleLines = 1; }
  83727. var _this = _super.call(this, scene, scaleLines) || this;
  83728. _this.pos = BABYLON.Vector3.Zero();
  83729. _this.xaxis = BABYLON.Vector3.Zero();
  83730. _this.yaxis = BABYLON.Vector3.Zero();
  83731. _this.zaxis = BABYLON.Vector3.Zero();
  83732. _this.mesh = mesh;
  83733. _this.bone = bone;
  83734. return _this;
  83735. }
  83736. BoneAxesViewer.prototype.update = function () {
  83737. if (!this.mesh || !this.bone) {
  83738. return;
  83739. }
  83740. var bone = this.bone;
  83741. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83742. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83743. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83744. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83745. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83746. };
  83747. BoneAxesViewer.prototype.dispose = function () {
  83748. if (this.mesh) {
  83749. this.mesh = null;
  83750. this.bone = null;
  83751. _super.prototype.dispose.call(this);
  83752. }
  83753. };
  83754. return BoneAxesViewer;
  83755. }(Debug.AxesViewer));
  83756. Debug.BoneAxesViewer = BoneAxesViewer;
  83757. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83758. })(BABYLON || (BABYLON = {}));
  83759. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83760. var BABYLON;
  83761. (function (BABYLON) {
  83762. var RayHelper = /** @class */ (function () {
  83763. function RayHelper(ray) {
  83764. this.ray = ray;
  83765. }
  83766. RayHelper.CreateAndShow = function (ray, scene, color) {
  83767. var helper = new RayHelper(ray);
  83768. helper.show(scene, color);
  83769. return helper;
  83770. };
  83771. RayHelper.prototype.show = function (scene, color) {
  83772. if (!this._renderFunction && this.ray) {
  83773. var ray = this.ray;
  83774. this._renderFunction = this._render.bind(this);
  83775. this._scene = scene;
  83776. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83777. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83778. if (this._renderFunction) {
  83779. this._scene.registerBeforeRender(this._renderFunction);
  83780. }
  83781. }
  83782. if (color && this._renderLine) {
  83783. this._renderLine.color.copyFrom(color);
  83784. }
  83785. };
  83786. RayHelper.prototype.hide = function () {
  83787. if (this._renderFunction && this._scene) {
  83788. this._scene.unregisterBeforeRender(this._renderFunction);
  83789. this._scene = null;
  83790. this._renderFunction = null;
  83791. if (this._renderLine) {
  83792. this._renderLine.dispose();
  83793. this._renderLine = null;
  83794. }
  83795. this._renderPoints = [];
  83796. }
  83797. };
  83798. RayHelper.prototype._render = function () {
  83799. var ray = this.ray;
  83800. if (!ray) {
  83801. return;
  83802. }
  83803. var point = this._renderPoints[1];
  83804. var len = Math.min(ray.length, 1000000);
  83805. point.copyFrom(ray.direction);
  83806. point.scaleInPlace(len);
  83807. point.addInPlace(ray.origin);
  83808. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83809. };
  83810. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83811. this._attachedToMesh = mesh;
  83812. var ray = this.ray;
  83813. if (!ray) {
  83814. return;
  83815. }
  83816. if (!ray.direction) {
  83817. ray.direction = BABYLON.Vector3.Zero();
  83818. }
  83819. if (!ray.origin) {
  83820. ray.origin = BABYLON.Vector3.Zero();
  83821. }
  83822. if (length) {
  83823. ray.length = length;
  83824. }
  83825. if (!meshSpaceOrigin) {
  83826. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83827. }
  83828. if (!meshSpaceDirection) {
  83829. // -1 so that this will work with Mesh.lookAt
  83830. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83831. }
  83832. if (!this._meshSpaceDirection) {
  83833. this._meshSpaceDirection = meshSpaceDirection.clone();
  83834. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83835. }
  83836. else {
  83837. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83838. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83839. }
  83840. if (!this._updateToMeshFunction) {
  83841. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83842. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83843. }
  83844. this._updateToMesh();
  83845. };
  83846. RayHelper.prototype.detachFromMesh = function () {
  83847. if (this._attachedToMesh) {
  83848. if (this._updateToMeshFunction) {
  83849. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83850. }
  83851. this._attachedToMesh = null;
  83852. this._updateToMeshFunction = null;
  83853. }
  83854. };
  83855. RayHelper.prototype._updateToMesh = function () {
  83856. var ray = this.ray;
  83857. if (!this._attachedToMesh || !ray) {
  83858. return;
  83859. }
  83860. if (this._attachedToMesh._isDisposed) {
  83861. this.detachFromMesh();
  83862. return;
  83863. }
  83864. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83865. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83866. };
  83867. RayHelper.prototype.dispose = function () {
  83868. this.hide();
  83869. this.detachFromMesh();
  83870. this.ray = null;
  83871. };
  83872. return RayHelper;
  83873. }());
  83874. BABYLON.RayHelper = RayHelper;
  83875. })(BABYLON || (BABYLON = {}));
  83876. //# sourceMappingURL=babylon.rayHelper.js.map
  83877. var BABYLON;
  83878. (function (BABYLON) {
  83879. // load the inspector using require, if not present in the global namespace.
  83880. var DebugLayer = /** @class */ (function () {
  83881. function DebugLayer(scene) {
  83882. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83883. this._scene = scene;
  83884. // load inspector using require, if it doesn't exist on the global namespace.
  83885. }
  83886. /** Creates the inspector window. */
  83887. DebugLayer.prototype._createInspector = function (config) {
  83888. if (config === void 0) { config = {}; }
  83889. var popup = config.popup || false;
  83890. var initialTab = config.initialTab || 0;
  83891. var parentElement = config.parentElement || null;
  83892. if (!this._inspector) {
  83893. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83894. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83895. } // else nothing to do,; instance is already existing
  83896. };
  83897. DebugLayer.prototype.isVisible = function () {
  83898. if (!this._inspector) {
  83899. return false;
  83900. }
  83901. return true;
  83902. };
  83903. DebugLayer.prototype.hide = function () {
  83904. if (this._inspector) {
  83905. try {
  83906. this._inspector.dispose();
  83907. }
  83908. catch (e) {
  83909. // If the inspector has been removed directly from the inspector tool
  83910. }
  83911. this._inspector = null;
  83912. }
  83913. };
  83914. DebugLayer.prototype.show = function (config) {
  83915. if (config === void 0) { config = {}; }
  83916. if (typeof this.BJSINSPECTOR == 'undefined') {
  83917. // Load inspector and add it to the DOM
  83918. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83919. }
  83920. else {
  83921. // Otherwise creates the inspector
  83922. this._createInspector(config);
  83923. }
  83924. };
  83925. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83926. return DebugLayer;
  83927. }());
  83928. BABYLON.DebugLayer = DebugLayer;
  83929. })(BABYLON || (BABYLON = {}));
  83930. //# sourceMappingURL=babylon.debugLayer.js.map
  83931. var BABYLON;
  83932. (function (BABYLON) {
  83933. var Debug;
  83934. (function (Debug) {
  83935. /**
  83936. * Used to show the physics impostor around the specific mesh.
  83937. */
  83938. var PhysicsViewer = /** @class */ (function () {
  83939. function PhysicsViewer(scene) {
  83940. this._impostors = [];
  83941. this._meshes = [];
  83942. this._numMeshes = 0;
  83943. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83944. var physicEngine = this._scene.getPhysicsEngine();
  83945. if (physicEngine) {
  83946. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83947. }
  83948. }
  83949. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83950. var plugin = this._physicsEnginePlugin;
  83951. for (var i = 0; i < this._numMeshes; i++) {
  83952. var impostor = this._impostors[i];
  83953. if (!impostor) {
  83954. continue;
  83955. }
  83956. if (impostor.isDisposed) {
  83957. this.hideImpostor(this._impostors[i--]);
  83958. }
  83959. else {
  83960. var mesh = this._meshes[i];
  83961. if (mesh && plugin) {
  83962. plugin.syncMeshWithImpostor(mesh, impostor);
  83963. }
  83964. }
  83965. }
  83966. };
  83967. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83968. if (!this._scene) {
  83969. return;
  83970. }
  83971. for (var i = 0; i < this._numMeshes; i++) {
  83972. if (this._impostors[i] == impostor) {
  83973. return;
  83974. }
  83975. }
  83976. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83977. if (debugMesh) {
  83978. this._impostors[this._numMeshes] = impostor;
  83979. this._meshes[this._numMeshes] = debugMesh;
  83980. if (this._numMeshes === 0) {
  83981. this._renderFunction = this._updateDebugMeshes.bind(this);
  83982. this._scene.registerBeforeRender(this._renderFunction);
  83983. }
  83984. this._numMeshes++;
  83985. }
  83986. };
  83987. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83988. if (!impostor || !this._scene) {
  83989. return;
  83990. }
  83991. var removed = false;
  83992. for (var i = 0; i < this._numMeshes; i++) {
  83993. if (this._impostors[i] == impostor) {
  83994. var mesh = this._meshes[i];
  83995. if (!mesh) {
  83996. continue;
  83997. }
  83998. this._scene.removeMesh(mesh);
  83999. mesh.dispose();
  84000. this._numMeshes--;
  84001. if (this._numMeshes > 0) {
  84002. this._meshes[i] = this._meshes[this._numMeshes];
  84003. this._impostors[i] = this._impostors[this._numMeshes];
  84004. this._meshes[this._numMeshes] = null;
  84005. this._impostors[this._numMeshes] = null;
  84006. }
  84007. else {
  84008. this._meshes[0] = null;
  84009. this._impostors[0] = null;
  84010. }
  84011. removed = true;
  84012. break;
  84013. }
  84014. }
  84015. if (removed && this._numMeshes === 0) {
  84016. this._scene.unregisterBeforeRender(this._renderFunction);
  84017. }
  84018. };
  84019. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84020. if (!this._debugMaterial) {
  84021. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84022. this._debugMaterial.wireframe = true;
  84023. }
  84024. return this._debugMaterial;
  84025. };
  84026. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84027. if (!this._debugBoxMesh) {
  84028. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84029. this._debugBoxMesh.renderingGroupId = 1;
  84030. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84031. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84032. scene.removeMesh(this._debugBoxMesh);
  84033. }
  84034. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84035. };
  84036. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84037. if (!this._debugSphereMesh) {
  84038. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84039. this._debugSphereMesh.renderingGroupId = 1;
  84040. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84041. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84042. scene.removeMesh(this._debugSphereMesh);
  84043. }
  84044. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84045. };
  84046. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84047. var mesh = null;
  84048. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84049. mesh = this._getDebugBoxMesh(scene);
  84050. impostor.getBoxSizeToRef(mesh.scaling);
  84051. }
  84052. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84053. mesh = this._getDebugSphereMesh(scene);
  84054. var radius = impostor.getRadius();
  84055. mesh.scaling.x = radius * 2;
  84056. mesh.scaling.y = radius * 2;
  84057. mesh.scaling.z = radius * 2;
  84058. }
  84059. return mesh;
  84060. };
  84061. PhysicsViewer.prototype.dispose = function () {
  84062. for (var i = 0; i < this._numMeshes; i++) {
  84063. this.hideImpostor(this._impostors[i]);
  84064. }
  84065. if (this._debugBoxMesh) {
  84066. this._debugBoxMesh.dispose();
  84067. }
  84068. if (this._debugSphereMesh) {
  84069. this._debugSphereMesh.dispose();
  84070. }
  84071. if (this._debugMaterial) {
  84072. this._debugMaterial.dispose();
  84073. }
  84074. this._impostors.length = 0;
  84075. this._scene = null;
  84076. this._physicsEnginePlugin = null;
  84077. };
  84078. return PhysicsViewer;
  84079. }());
  84080. Debug.PhysicsViewer = PhysicsViewer;
  84081. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84082. })(BABYLON || (BABYLON = {}));
  84083. //# sourceMappingURL=babylon.physicsViewer.js.map
  84084. var BABYLON;
  84085. (function (BABYLON) {
  84086. var BoundingBoxRenderer = /** @class */ (function () {
  84087. function BoundingBoxRenderer(scene) {
  84088. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84089. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84090. this.showBackLines = true;
  84091. this.renderList = new BABYLON.SmartArray(32);
  84092. this._vertexBuffers = {};
  84093. this._scene = scene;
  84094. }
  84095. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84096. if (this._colorShader) {
  84097. return;
  84098. }
  84099. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84100. attributes: [BABYLON.VertexBuffer.PositionKind],
  84101. uniforms: ["world", "viewProjection", "color"]
  84102. });
  84103. var engine = this._scene.getEngine();
  84104. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84106. this._createIndexBuffer();
  84107. };
  84108. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84109. var engine = this._scene.getEngine();
  84110. 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]);
  84111. };
  84112. BoundingBoxRenderer.prototype._rebuild = function () {
  84113. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84114. if (vb) {
  84115. vb._rebuild();
  84116. }
  84117. this._createIndexBuffer();
  84118. };
  84119. BoundingBoxRenderer.prototype.reset = function () {
  84120. this.renderList.reset();
  84121. };
  84122. BoundingBoxRenderer.prototype.render = function () {
  84123. if (this.renderList.length === 0) {
  84124. return;
  84125. }
  84126. this._prepareRessources();
  84127. if (!this._colorShader.isReady()) {
  84128. return;
  84129. }
  84130. var engine = this._scene.getEngine();
  84131. engine.setDepthWrite(false);
  84132. this._colorShader._preBind();
  84133. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84134. var boundingBox = this.renderList.data[boundingBoxIndex];
  84135. var min = boundingBox.minimum;
  84136. var max = boundingBox.maximum;
  84137. var diff = max.subtract(min);
  84138. var median = min.add(diff.scale(0.5));
  84139. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84140. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84141. .multiply(boundingBox.getWorldMatrix());
  84142. // VBOs
  84143. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84144. if (this.showBackLines) {
  84145. // Back
  84146. engine.setDepthFunctionToGreaterOrEqual();
  84147. this._scene.resetCachedMaterial();
  84148. this._colorShader.setColor4("color", this.backColor.toColor4());
  84149. this._colorShader.bind(worldMatrix);
  84150. // Draw order
  84151. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84152. }
  84153. // Front
  84154. engine.setDepthFunctionToLess();
  84155. this._scene.resetCachedMaterial();
  84156. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84157. this._colorShader.bind(worldMatrix);
  84158. // Draw order
  84159. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84160. }
  84161. this._colorShader.unbind();
  84162. engine.setDepthFunctionToLessOrEqual();
  84163. engine.setDepthWrite(true);
  84164. };
  84165. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84166. this._prepareRessources();
  84167. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84168. return;
  84169. }
  84170. var engine = this._scene.getEngine();
  84171. engine.setDepthWrite(false);
  84172. engine.setColorWrite(false);
  84173. this._colorShader._preBind();
  84174. var boundingBox = mesh._boundingInfo.boundingBox;
  84175. var min = boundingBox.minimum;
  84176. var max = boundingBox.maximum;
  84177. var diff = max.subtract(min);
  84178. var median = min.add(diff.scale(0.5));
  84179. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84180. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84181. .multiply(boundingBox.getWorldMatrix());
  84182. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84183. engine.setDepthFunctionToLess();
  84184. this._scene.resetCachedMaterial();
  84185. this._colorShader.bind(worldMatrix);
  84186. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84187. this._colorShader.unbind();
  84188. engine.setDepthFunctionToLessOrEqual();
  84189. engine.setDepthWrite(true);
  84190. engine.setColorWrite(true);
  84191. };
  84192. BoundingBoxRenderer.prototype.dispose = function () {
  84193. if (!this._colorShader) {
  84194. return;
  84195. }
  84196. this.renderList.dispose();
  84197. this._colorShader.dispose();
  84198. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84199. if (buffer) {
  84200. buffer.dispose();
  84201. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84202. }
  84203. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84204. };
  84205. return BoundingBoxRenderer;
  84206. }());
  84207. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84208. })(BABYLON || (BABYLON = {}));
  84209. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84210. var BABYLON;
  84211. (function (BABYLON) {
  84212. /**
  84213. * Defines a target to use with MorphTargetManager
  84214. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84215. */
  84216. var MorphTarget = /** @class */ (function () {
  84217. /**
  84218. * Creates a new MorphTarget
  84219. * @param name defines the name of the target
  84220. * @param influence defines the influence to use
  84221. */
  84222. function MorphTarget(
  84223. /** defines the name of the target */
  84224. name, influence) {
  84225. if (influence === void 0) { influence = 0; }
  84226. this.name = name;
  84227. /**
  84228. * Gets or sets the list of animations
  84229. */
  84230. this.animations = new Array();
  84231. this._positions = null;
  84232. this._normals = null;
  84233. this._tangents = null;
  84234. /**
  84235. * Observable raised when the influence changes
  84236. */
  84237. this.onInfluenceChanged = new BABYLON.Observable();
  84238. this.influence = influence;
  84239. }
  84240. Object.defineProperty(MorphTarget.prototype, "influence", {
  84241. /**
  84242. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84243. */
  84244. get: function () {
  84245. return this._influence;
  84246. },
  84247. set: function (influence) {
  84248. if (this._influence === influence) {
  84249. return;
  84250. }
  84251. var previous = this._influence;
  84252. this._influence = influence;
  84253. if (this.onInfluenceChanged.hasObservers) {
  84254. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84255. }
  84256. },
  84257. enumerable: true,
  84258. configurable: true
  84259. });
  84260. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84261. /**
  84262. * Gets a boolean defining if the target contains position data
  84263. */
  84264. get: function () {
  84265. return !!this._positions;
  84266. },
  84267. enumerable: true,
  84268. configurable: true
  84269. });
  84270. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84271. /**
  84272. * Gets a boolean defining if the target contains normal data
  84273. */
  84274. get: function () {
  84275. return !!this._normals;
  84276. },
  84277. enumerable: true,
  84278. configurable: true
  84279. });
  84280. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84281. /**
  84282. * Gets a boolean defining if the target contains tangent data
  84283. */
  84284. get: function () {
  84285. return !!this._tangents;
  84286. },
  84287. enumerable: true,
  84288. configurable: true
  84289. });
  84290. /**
  84291. * Affects position data to this target
  84292. * @param data defines the position data to use
  84293. */
  84294. MorphTarget.prototype.setPositions = function (data) {
  84295. this._positions = data;
  84296. };
  84297. /**
  84298. * Gets the position data stored in this target
  84299. * @returns a FloatArray containing the position data (or null if not present)
  84300. */
  84301. MorphTarget.prototype.getPositions = function () {
  84302. return this._positions;
  84303. };
  84304. /**
  84305. * Affects normal data to this target
  84306. * @param data defines the normal data to use
  84307. */
  84308. MorphTarget.prototype.setNormals = function (data) {
  84309. this._normals = data;
  84310. };
  84311. /**
  84312. * Gets the normal data stored in this target
  84313. * @returns a FloatArray containing the normal data (or null if not present)
  84314. */
  84315. MorphTarget.prototype.getNormals = function () {
  84316. return this._normals;
  84317. };
  84318. /**
  84319. * Affects tangent data to this target
  84320. * @param data defines the tangent data to use
  84321. */
  84322. MorphTarget.prototype.setTangents = function (data) {
  84323. this._tangents = data;
  84324. };
  84325. /**
  84326. * Gets the tangent data stored in this target
  84327. * @returns a FloatArray containing the tangent data (or null if not present)
  84328. */
  84329. MorphTarget.prototype.getTangents = function () {
  84330. return this._tangents;
  84331. };
  84332. /**
  84333. * Serializes the current target into a Serialization object
  84334. * @returns the serialized object
  84335. */
  84336. MorphTarget.prototype.serialize = function () {
  84337. var serializationObject = {};
  84338. serializationObject.name = this.name;
  84339. serializationObject.influence = this.influence;
  84340. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  84341. if (this.hasNormals) {
  84342. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  84343. }
  84344. if (this.hasTangents) {
  84345. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  84346. }
  84347. // Animations
  84348. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  84349. return serializationObject;
  84350. };
  84351. // Statics
  84352. /**
  84353. * Creates a new target from serialized data
  84354. * @param serializationObject defines the serialized data to use
  84355. * @returns a new MorphTarget
  84356. */
  84357. MorphTarget.Parse = function (serializationObject) {
  84358. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  84359. result.setPositions(serializationObject.positions);
  84360. if (serializationObject.normals) {
  84361. result.setNormals(serializationObject.normals);
  84362. }
  84363. if (serializationObject.tangents) {
  84364. result.setTangents(serializationObject.tangents);
  84365. }
  84366. // Animations
  84367. if (serializationObject.animations) {
  84368. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  84369. var parsedAnimation = serializationObject.animations[animationIndex];
  84370. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  84371. }
  84372. }
  84373. return result;
  84374. };
  84375. /**
  84376. * Creates a MorphTarget from mesh data
  84377. * @param mesh defines the source mesh
  84378. * @param name defines the name to use for the new target
  84379. * @param influence defines the influence to attach to the target
  84380. * @returns a new MorphTarget
  84381. */
  84382. MorphTarget.FromMesh = function (mesh, name, influence) {
  84383. if (!name) {
  84384. name = mesh.name;
  84385. }
  84386. var result = new MorphTarget(name, influence);
  84387. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84389. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  84390. }
  84391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  84392. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  84393. }
  84394. return result;
  84395. };
  84396. return MorphTarget;
  84397. }());
  84398. BABYLON.MorphTarget = MorphTarget;
  84399. })(BABYLON || (BABYLON = {}));
  84400. //# sourceMappingURL=babylon.morphTarget.js.map
  84401. var BABYLON;
  84402. (function (BABYLON) {
  84403. /**
  84404. * This class is used to deform meshes using morphing between different targets
  84405. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84406. */
  84407. var MorphTargetManager = /** @class */ (function () {
  84408. /**
  84409. * Creates a new MorphTargetManager
  84410. * @param scene defines the current scene
  84411. */
  84412. function MorphTargetManager(scene) {
  84413. if (scene === void 0) { scene = null; }
  84414. this._targets = new Array();
  84415. this._targetObservable = new Array();
  84416. this._activeTargets = new BABYLON.SmartArray(16);
  84417. this._supportsNormals = false;
  84418. this._supportsTangents = false;
  84419. this._vertexCount = 0;
  84420. this._uniqueId = 0;
  84421. this._tempInfluences = new Array();
  84422. if (!scene) {
  84423. scene = BABYLON.Engine.LastCreatedScene;
  84424. }
  84425. this._scene = scene;
  84426. if (this._scene) {
  84427. this._scene.morphTargetManagers.push(this);
  84428. this._uniqueId = this._scene.getUniqueId();
  84429. }
  84430. }
  84431. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  84432. /**
  84433. * Gets the unique ID of this manager
  84434. */
  84435. get: function () {
  84436. return this._uniqueId;
  84437. },
  84438. enumerable: true,
  84439. configurable: true
  84440. });
  84441. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  84442. /**
  84443. * Gets the number of vertices handled by this manager
  84444. */
  84445. get: function () {
  84446. return this._vertexCount;
  84447. },
  84448. enumerable: true,
  84449. configurable: true
  84450. });
  84451. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  84452. /**
  84453. * Gets a boolean indicating if this manager supports morphing of normals
  84454. */
  84455. get: function () {
  84456. return this._supportsNormals;
  84457. },
  84458. enumerable: true,
  84459. configurable: true
  84460. });
  84461. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  84462. /**
  84463. * Gets a boolean indicating if this manager supports morphing of tangents
  84464. */
  84465. get: function () {
  84466. return this._supportsTangents;
  84467. },
  84468. enumerable: true,
  84469. configurable: true
  84470. });
  84471. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  84472. /**
  84473. * Gets the number of targets stored in this manager
  84474. */
  84475. get: function () {
  84476. return this._targets.length;
  84477. },
  84478. enumerable: true,
  84479. configurable: true
  84480. });
  84481. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  84482. /**
  84483. * Gets the number of influencers (ie. the number of targets with influences > 0)
  84484. */
  84485. get: function () {
  84486. return this._activeTargets.length;
  84487. },
  84488. enumerable: true,
  84489. configurable: true
  84490. });
  84491. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  84492. /**
  84493. * Gets the list of influences (one per target)
  84494. */
  84495. get: function () {
  84496. return this._influences;
  84497. },
  84498. enumerable: true,
  84499. configurable: true
  84500. });
  84501. /**
  84502. * Gets the active target at specified index. An active target is a target with an influence > 0
  84503. * @param index defines the index to check
  84504. * @returns the requested target
  84505. */
  84506. MorphTargetManager.prototype.getActiveTarget = function (index) {
  84507. return this._activeTargets.data[index];
  84508. };
  84509. /**
  84510. * Gets the target at specified index
  84511. * @param index defines the index to check
  84512. * @returns the requested target
  84513. */
  84514. MorphTargetManager.prototype.getTarget = function (index) {
  84515. return this._targets[index];
  84516. };
  84517. /**
  84518. * Add a new target to this manager
  84519. * @param target defines the target to add
  84520. */
  84521. MorphTargetManager.prototype.addTarget = function (target) {
  84522. var _this = this;
  84523. this._targets.push(target);
  84524. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  84525. _this._syncActiveTargets(needUpdate);
  84526. }));
  84527. this._syncActiveTargets(true);
  84528. };
  84529. /**
  84530. * Removes a target from the manager
  84531. * @param target defines the target to remove
  84532. */
  84533. MorphTargetManager.prototype.removeTarget = function (target) {
  84534. var index = this._targets.indexOf(target);
  84535. if (index >= 0) {
  84536. this._targets.splice(index, 1);
  84537. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  84538. this._syncActiveTargets(true);
  84539. }
  84540. };
  84541. /**
  84542. * Serializes the current manager into a Serialization object
  84543. * @returns the serialized object
  84544. */
  84545. MorphTargetManager.prototype.serialize = function () {
  84546. var serializationObject = {};
  84547. serializationObject.id = this.uniqueId;
  84548. serializationObject.targets = [];
  84549. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84550. var target = _a[_i];
  84551. serializationObject.targets.push(target.serialize());
  84552. }
  84553. return serializationObject;
  84554. };
  84555. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  84556. var influenceCount = 0;
  84557. this._activeTargets.reset();
  84558. this._supportsNormals = true;
  84559. this._supportsTangents = true;
  84560. this._vertexCount = 0;
  84561. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84562. var target = _a[_i];
  84563. this._activeTargets.push(target);
  84564. this._tempInfluences[influenceCount++] = target.influence;
  84565. var positions = target.getPositions();
  84566. if (positions) {
  84567. this._supportsNormals = this._supportsNormals && target.hasNormals;
  84568. this._supportsTangents = this._supportsTangents && target.hasTangents;
  84569. var vertexCount = positions.length / 3;
  84570. if (this._vertexCount === 0) {
  84571. this._vertexCount = vertexCount;
  84572. }
  84573. else if (this._vertexCount !== vertexCount) {
  84574. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  84575. return;
  84576. }
  84577. }
  84578. }
  84579. if (!this._influences || this._influences.length !== influenceCount) {
  84580. this._influences = new Float32Array(influenceCount);
  84581. }
  84582. for (var index = 0; index < influenceCount; index++) {
  84583. this._influences[index] = this._tempInfluences[index];
  84584. }
  84585. if (needUpdate) {
  84586. this.synchronize();
  84587. }
  84588. };
  84589. /**
  84590. * Syncrhonize the targets with all the meshes using this morph target manager
  84591. */
  84592. MorphTargetManager.prototype.synchronize = function () {
  84593. if (!this._scene) {
  84594. return;
  84595. }
  84596. // Flag meshes as dirty to resync with the active targets
  84597. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  84598. var mesh = _a[_i];
  84599. if (mesh.morphTargetManager === this) {
  84600. mesh._syncGeometryWithMorphTargetManager();
  84601. }
  84602. }
  84603. };
  84604. // Statics
  84605. /**
  84606. * Creates a new MorphTargetManager from serialized data
  84607. * @param serializationObject defines the serialized data
  84608. * @param scene defines the hosting scene
  84609. * @returns the new MorphTargetManager
  84610. */
  84611. MorphTargetManager.Parse = function (serializationObject, scene) {
  84612. var result = new MorphTargetManager(scene);
  84613. result._uniqueId = serializationObject.id;
  84614. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84615. var targetData = _a[_i];
  84616. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84617. }
  84618. return result;
  84619. };
  84620. return MorphTargetManager;
  84621. }());
  84622. BABYLON.MorphTargetManager = MorphTargetManager;
  84623. })(BABYLON || (BABYLON = {}));
  84624. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84625. var BABYLON;
  84626. (function (BABYLON) {
  84627. var Octree = /** @class */ (function () {
  84628. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84629. if (maxDepth === void 0) { maxDepth = 2; }
  84630. this.maxDepth = maxDepth;
  84631. this.dynamicContent = new Array();
  84632. this._maxBlockCapacity = maxBlockCapacity || 64;
  84633. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84634. this._creationFunc = creationFunc;
  84635. }
  84636. // Methods
  84637. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84638. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84639. };
  84640. Octree.prototype.addMesh = function (entry) {
  84641. for (var index = 0; index < this.blocks.length; index++) {
  84642. var block = this.blocks[index];
  84643. block.addEntry(entry);
  84644. }
  84645. };
  84646. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84647. this._selectionContent.reset();
  84648. for (var index = 0; index < this.blocks.length; index++) {
  84649. var block = this.blocks[index];
  84650. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84651. }
  84652. if (allowDuplicate) {
  84653. this._selectionContent.concat(this.dynamicContent);
  84654. }
  84655. else {
  84656. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84657. }
  84658. return this._selectionContent;
  84659. };
  84660. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84661. this._selectionContent.reset();
  84662. for (var index = 0; index < this.blocks.length; index++) {
  84663. var block = this.blocks[index];
  84664. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84665. }
  84666. if (allowDuplicate) {
  84667. this._selectionContent.concat(this.dynamicContent);
  84668. }
  84669. else {
  84670. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84671. }
  84672. return this._selectionContent;
  84673. };
  84674. Octree.prototype.intersectsRay = function (ray) {
  84675. this._selectionContent.reset();
  84676. for (var index = 0; index < this.blocks.length; index++) {
  84677. var block = this.blocks[index];
  84678. block.intersectsRay(ray, this._selectionContent);
  84679. }
  84680. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84681. return this._selectionContent;
  84682. };
  84683. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84684. target.blocks = new Array();
  84685. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84686. // Segmenting space
  84687. for (var x = 0; x < 2; x++) {
  84688. for (var y = 0; y < 2; y++) {
  84689. for (var z = 0; z < 2; z++) {
  84690. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84691. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84692. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84693. block.addEntries(entries);
  84694. target.blocks.push(block);
  84695. }
  84696. }
  84697. }
  84698. };
  84699. Octree.CreationFuncForMeshes = function (entry, block) {
  84700. var boundingInfo = entry.getBoundingInfo();
  84701. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84702. block.entries.push(entry);
  84703. }
  84704. };
  84705. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84706. var boundingInfo = entry.getBoundingInfo();
  84707. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84708. block.entries.push(entry);
  84709. }
  84710. };
  84711. return Octree;
  84712. }());
  84713. BABYLON.Octree = Octree;
  84714. })(BABYLON || (BABYLON = {}));
  84715. //# sourceMappingURL=babylon.octree.js.map
  84716. var BABYLON;
  84717. (function (BABYLON) {
  84718. var OctreeBlock = /** @class */ (function () {
  84719. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84720. this.entries = new Array();
  84721. this._boundingVectors = new Array();
  84722. this._capacity = capacity;
  84723. this._depth = depth;
  84724. this._maxDepth = maxDepth;
  84725. this._creationFunc = creationFunc;
  84726. this._minPoint = minPoint;
  84727. this._maxPoint = maxPoint;
  84728. this._boundingVectors.push(minPoint.clone());
  84729. this._boundingVectors.push(maxPoint.clone());
  84730. this._boundingVectors.push(minPoint.clone());
  84731. this._boundingVectors[2].x = maxPoint.x;
  84732. this._boundingVectors.push(minPoint.clone());
  84733. this._boundingVectors[3].y = maxPoint.y;
  84734. this._boundingVectors.push(minPoint.clone());
  84735. this._boundingVectors[4].z = maxPoint.z;
  84736. this._boundingVectors.push(maxPoint.clone());
  84737. this._boundingVectors[5].z = minPoint.z;
  84738. this._boundingVectors.push(maxPoint.clone());
  84739. this._boundingVectors[6].x = minPoint.x;
  84740. this._boundingVectors.push(maxPoint.clone());
  84741. this._boundingVectors[7].y = minPoint.y;
  84742. }
  84743. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84744. // Property
  84745. get: function () {
  84746. return this._capacity;
  84747. },
  84748. enumerable: true,
  84749. configurable: true
  84750. });
  84751. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84752. get: function () {
  84753. return this._minPoint;
  84754. },
  84755. enumerable: true,
  84756. configurable: true
  84757. });
  84758. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84759. get: function () {
  84760. return this._maxPoint;
  84761. },
  84762. enumerable: true,
  84763. configurable: true
  84764. });
  84765. // Methods
  84766. OctreeBlock.prototype.addEntry = function (entry) {
  84767. if (this.blocks) {
  84768. for (var index = 0; index < this.blocks.length; index++) {
  84769. var block = this.blocks[index];
  84770. block.addEntry(entry);
  84771. }
  84772. return;
  84773. }
  84774. this._creationFunc(entry, this);
  84775. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84776. this.createInnerBlocks();
  84777. }
  84778. };
  84779. OctreeBlock.prototype.addEntries = function (entries) {
  84780. for (var index = 0; index < entries.length; index++) {
  84781. var mesh = entries[index];
  84782. this.addEntry(mesh);
  84783. }
  84784. };
  84785. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84786. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84787. if (this.blocks) {
  84788. for (var index = 0; index < this.blocks.length; index++) {
  84789. var block = this.blocks[index];
  84790. block.select(frustumPlanes, selection, allowDuplicate);
  84791. }
  84792. return;
  84793. }
  84794. if (allowDuplicate) {
  84795. selection.concat(this.entries);
  84796. }
  84797. else {
  84798. selection.concatWithNoDuplicate(this.entries);
  84799. }
  84800. }
  84801. };
  84802. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84803. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84804. if (this.blocks) {
  84805. for (var index = 0; index < this.blocks.length; index++) {
  84806. var block = this.blocks[index];
  84807. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84808. }
  84809. return;
  84810. }
  84811. if (allowDuplicate) {
  84812. selection.concat(this.entries);
  84813. }
  84814. else {
  84815. selection.concatWithNoDuplicate(this.entries);
  84816. }
  84817. }
  84818. };
  84819. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84820. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84821. if (this.blocks) {
  84822. for (var index = 0; index < this.blocks.length; index++) {
  84823. var block = this.blocks[index];
  84824. block.intersectsRay(ray, selection);
  84825. }
  84826. return;
  84827. }
  84828. selection.concatWithNoDuplicate(this.entries);
  84829. }
  84830. };
  84831. OctreeBlock.prototype.createInnerBlocks = function () {
  84832. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84833. };
  84834. return OctreeBlock;
  84835. }());
  84836. BABYLON.OctreeBlock = OctreeBlock;
  84837. })(BABYLON || (BABYLON = {}));
  84838. //# sourceMappingURL=babylon.octreeBlock.js.map
  84839. var BABYLON;
  84840. (function (BABYLON) {
  84841. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84842. __extends(VRDistortionCorrectionPostProcess, _super);
  84843. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84844. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84845. 'LensCenter',
  84846. 'Scale',
  84847. 'ScaleIn',
  84848. 'HmdWarpParam'
  84849. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84850. _this._isRightEye = isRightEye;
  84851. _this._distortionFactors = vrMetrics.distortionK;
  84852. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84853. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84854. _this.adaptScaleToCurrentViewport = true;
  84855. _this.onSizeChangedObservable.add(function () {
  84856. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84857. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84858. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84859. });
  84860. _this.onApplyObservable.add(function (effect) {
  84861. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84862. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84863. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84864. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84865. });
  84866. return _this;
  84867. }
  84868. return VRDistortionCorrectionPostProcess;
  84869. }(BABYLON.PostProcess));
  84870. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84871. })(BABYLON || (BABYLON = {}));
  84872. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84873. var BABYLON;
  84874. (function (BABYLON) {
  84875. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84876. __extends(AnaglyphPostProcess, _super);
  84877. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84878. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84879. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84880. _this.onApplyObservable.add(function (effect) {
  84881. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84882. });
  84883. return _this;
  84884. }
  84885. return AnaglyphPostProcess;
  84886. }(BABYLON.PostProcess));
  84887. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84888. })(BABYLON || (BABYLON = {}));
  84889. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84890. var BABYLON;
  84891. (function (BABYLON) {
  84892. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  84893. __extends(StereoscopicInterlacePostProcess, _super);
  84894. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  84895. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  84896. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84897. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84898. _this.onSizeChangedObservable.add(function () {
  84899. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84900. });
  84901. _this.onApplyObservable.add(function (effect) {
  84902. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  84903. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  84904. });
  84905. return _this;
  84906. }
  84907. return StereoscopicInterlacePostProcess;
  84908. }(BABYLON.PostProcess));
  84909. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  84910. })(BABYLON || (BABYLON = {}));
  84911. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  84912. var BABYLON;
  84913. (function (BABYLON) {
  84914. /**
  84915. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  84916. * Screen rotation is taken into account.
  84917. */
  84918. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  84919. function FreeCameraDeviceOrientationInput() {
  84920. var _this = this;
  84921. this._screenOrientationAngle = 0;
  84922. this._screenQuaternion = new BABYLON.Quaternion();
  84923. this._alpha = 0;
  84924. this._beta = 0;
  84925. this._gamma = 0;
  84926. this._orientationChanged = function () {
  84927. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  84928. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  84929. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  84930. };
  84931. this._deviceOrientation = function (evt) {
  84932. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  84933. _this._beta = evt.beta !== null ? evt.beta : 0;
  84934. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  84935. };
  84936. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  84937. this._orientationChanged();
  84938. }
  84939. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  84940. get: function () {
  84941. return this._camera;
  84942. },
  84943. set: function (camera) {
  84944. this._camera = camera;
  84945. if (this._camera != null && !this._camera.rotationQuaternion) {
  84946. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  84947. }
  84948. },
  84949. enumerable: true,
  84950. configurable: true
  84951. });
  84952. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84953. window.addEventListener("orientationchange", this._orientationChanged);
  84954. window.addEventListener("deviceorientation", this._deviceOrientation);
  84955. //In certain cases, the attach control is called AFTER orientation was changed,
  84956. //So this is needed.
  84957. this._orientationChanged();
  84958. };
  84959. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  84960. window.removeEventListener("orientationchange", this._orientationChanged);
  84961. window.removeEventListener("deviceorientation", this._deviceOrientation);
  84962. };
  84963. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  84964. //if no device orientation provided, don't update the rotation.
  84965. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  84966. if (!this._alpha)
  84967. return;
  84968. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  84969. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  84970. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  84971. //Mirror on XY Plane
  84972. this._camera.rotationQuaternion.z *= -1;
  84973. this._camera.rotationQuaternion.w *= -1;
  84974. };
  84975. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  84976. return "FreeCameraDeviceOrientationInput";
  84977. };
  84978. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  84979. return "deviceOrientation";
  84980. };
  84981. return FreeCameraDeviceOrientationInput;
  84982. }());
  84983. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  84984. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  84985. })(BABYLON || (BABYLON = {}));
  84986. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  84987. var BABYLON;
  84988. (function (BABYLON) {
  84989. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  84990. function ArcRotateCameraVRDeviceOrientationInput() {
  84991. this.alphaCorrection = 1;
  84992. this.betaCorrection = 1;
  84993. this.gammaCorrection = 1;
  84994. this._alpha = 0;
  84995. this._gamma = 0;
  84996. this._dirty = false;
  84997. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  84998. }
  84999. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85000. this.camera.attachControl(element, noPreventDefault);
  85001. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85002. };
  85003. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85004. if (evt.alpha !== null) {
  85005. this._alpha = +evt.alpha | 0;
  85006. }
  85007. if (evt.gamma !== null) {
  85008. this._gamma = +evt.gamma | 0;
  85009. }
  85010. this._dirty = true;
  85011. };
  85012. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85013. if (this._dirty) {
  85014. this._dirty = false;
  85015. if (this._gamma < 0) {
  85016. this._gamma = 180 + this._gamma;
  85017. }
  85018. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85019. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85020. }
  85021. };
  85022. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85023. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85024. };
  85025. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85026. return "ArcRotateCameraVRDeviceOrientationInput";
  85027. };
  85028. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85029. return "VRDeviceOrientation";
  85030. };
  85031. return ArcRotateCameraVRDeviceOrientationInput;
  85032. }());
  85033. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85034. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85035. })(BABYLON || (BABYLON = {}));
  85036. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85037. var BABYLON;
  85038. (function (BABYLON) {
  85039. var VRCameraMetrics = /** @class */ (function () {
  85040. function VRCameraMetrics() {
  85041. this.compensateDistortion = true;
  85042. }
  85043. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85044. get: function () {
  85045. return this.hResolution / (2 * this.vResolution);
  85046. },
  85047. enumerable: true,
  85048. configurable: true
  85049. });
  85050. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85051. get: function () {
  85052. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85053. },
  85054. enumerable: true,
  85055. configurable: true
  85056. });
  85057. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85058. get: function () {
  85059. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85060. var h = (4 * meters) / this.hScreenSize;
  85061. return BABYLON.Matrix.Translation(h, 0, 0);
  85062. },
  85063. enumerable: true,
  85064. configurable: true
  85065. });
  85066. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85067. get: function () {
  85068. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85069. var h = (4 * meters) / this.hScreenSize;
  85070. return BABYLON.Matrix.Translation(-h, 0, 0);
  85071. },
  85072. enumerable: true,
  85073. configurable: true
  85074. });
  85075. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85076. get: function () {
  85077. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85078. },
  85079. enumerable: true,
  85080. configurable: true
  85081. });
  85082. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85083. get: function () {
  85084. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85085. },
  85086. enumerable: true,
  85087. configurable: true
  85088. });
  85089. VRCameraMetrics.GetDefault = function () {
  85090. var result = new VRCameraMetrics();
  85091. result.hResolution = 1280;
  85092. result.vResolution = 800;
  85093. result.hScreenSize = 0.149759993;
  85094. result.vScreenSize = 0.0935999975;
  85095. result.vScreenCenter = 0.0467999987;
  85096. result.eyeToScreenDistance = 0.0410000011;
  85097. result.lensSeparationDistance = 0.0635000020;
  85098. result.interpupillaryDistance = 0.0640000030;
  85099. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85100. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85101. result.postProcessScaleFactor = 1.714605507808412;
  85102. result.lensCenterOffset = 0.151976421;
  85103. return result;
  85104. };
  85105. return VRCameraMetrics;
  85106. }());
  85107. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85108. })(BABYLON || (BABYLON = {}));
  85109. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85110. var BABYLON;
  85111. (function (BABYLON) {
  85112. /**
  85113. * This represents a WebVR camera.
  85114. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85115. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85116. */
  85117. var WebVRFreeCamera = /** @class */ (function (_super) {
  85118. __extends(WebVRFreeCamera, _super);
  85119. /**
  85120. * Instantiates a WebVRFreeCamera.
  85121. * @param name The name of the WebVRFreeCamera
  85122. * @param position The starting anchor position for the camera
  85123. * @param scene The scene the camera belongs to
  85124. * @param webVROptions a set of customizable options for the webVRCamera
  85125. */
  85126. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85127. if (webVROptions === void 0) { webVROptions = {}; }
  85128. var _this = _super.call(this, name, position, scene) || this;
  85129. _this.webVROptions = webVROptions;
  85130. /**
  85131. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85132. */
  85133. _this._vrDevice = null;
  85134. /**
  85135. * The rawPose of the vrDevice.
  85136. */
  85137. _this.rawPose = null;
  85138. _this._specsVersion = "1.1";
  85139. _this._attached = false;
  85140. _this._descendants = [];
  85141. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85142. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85143. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85144. _this._standingMatrix = null;
  85145. /**
  85146. * Represents device position in babylon space.
  85147. */
  85148. _this.devicePosition = BABYLON.Vector3.Zero();
  85149. /**
  85150. * Represents device rotation in babylon space.
  85151. */
  85152. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85153. /**
  85154. * The scale of the device to be used when translating from device space to babylon space.
  85155. */
  85156. _this.deviceScaleFactor = 1;
  85157. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85158. _this._worldToDevice = BABYLON.Matrix.Identity();
  85159. /**
  85160. * References to the webVR controllers for the vrDevice.
  85161. */
  85162. _this.controllers = [];
  85163. /**
  85164. * Emits an event when a controller is attached.
  85165. */
  85166. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85167. /**
  85168. * Emits an event when a controller's mesh has been loaded;
  85169. */
  85170. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85171. /**
  85172. * If the rig cameras be used as parent instead of this camera.
  85173. */
  85174. _this.rigParenting = true;
  85175. _this._defaultHeight = undefined;
  85176. _this._workingVector = BABYLON.Vector3.Zero();
  85177. _this._oneVector = BABYLON.Vector3.One();
  85178. _this._workingMatrix = BABYLON.Matrix.Identity();
  85179. _this._cache.position = BABYLON.Vector3.Zero();
  85180. if (webVROptions.defaultHeight) {
  85181. _this._defaultHeight = webVROptions.defaultHeight;
  85182. _this.position.y = _this._defaultHeight;
  85183. }
  85184. _this.minZ = 0.1;
  85185. //legacy support - the compensation boolean was removed.
  85186. if (arguments.length === 5) {
  85187. _this.webVROptions = arguments[4];
  85188. }
  85189. // default webVR options
  85190. if (_this.webVROptions.trackPosition == undefined) {
  85191. _this.webVROptions.trackPosition = true;
  85192. }
  85193. if (_this.webVROptions.controllerMeshes == undefined) {
  85194. _this.webVROptions.controllerMeshes = true;
  85195. }
  85196. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85197. _this.webVROptions.defaultLightingOnControllers = true;
  85198. }
  85199. _this.rotationQuaternion = new BABYLON.Quaternion();
  85200. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85201. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85202. }
  85203. //enable VR
  85204. var engine = _this.getEngine();
  85205. _this._onVREnabled = function (success) { if (success) {
  85206. _this.initControllers();
  85207. } };
  85208. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85209. engine.initWebVR().add(function (event) {
  85210. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85211. return;
  85212. }
  85213. _this._vrDevice = event.vrDisplay;
  85214. //reset the rig parameters.
  85215. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85216. if (_this._attached) {
  85217. _this.getEngine().enableVR();
  85218. }
  85219. });
  85220. if (typeof (VRFrameData) !== "undefined")
  85221. _this._frameData = new VRFrameData();
  85222. /**
  85223. * The idea behind the following lines:
  85224. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85225. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85226. * the second will not show it correctly.
  85227. *
  85228. * To solve this - each object that has the camera as parent will be added to a protected array.
  85229. * When the rig camera renders, it will take this array and set all of those to be its children.
  85230. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85231. * Amazing!
  85232. */
  85233. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85234. if (camera.parent === _this && _this.rigParenting) {
  85235. _this._descendants = _this.getDescendants(true, function (n) {
  85236. // don't take the cameras or the controllers!
  85237. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85238. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85239. return !isController && !isRigCamera;
  85240. });
  85241. _this._descendants.forEach(function (node) {
  85242. node.parent = camera;
  85243. });
  85244. }
  85245. });
  85246. scene.onAfterCameraRenderObservable.add(function (camera) {
  85247. if (camera.parent === _this && _this.rigParenting) {
  85248. _this._descendants.forEach(function (node) {
  85249. node.parent = _this;
  85250. });
  85251. }
  85252. });
  85253. return _this;
  85254. }
  85255. /**
  85256. * Gets the device distance from the ground in meters.
  85257. * @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.
  85258. */
  85259. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85260. if (this._standingMatrix) {
  85261. // Add standing matrix offset to get real offset from ground in room
  85262. this._standingMatrix.getTranslationToRef(this._workingVector);
  85263. return this._deviceRoomPosition.y + this._workingVector.y;
  85264. }
  85265. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85266. return this._defaultHeight || 0;
  85267. };
  85268. /**
  85269. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85270. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85271. */
  85272. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85273. var _this = this;
  85274. if (callback === void 0) { callback = function (bool) { }; }
  85275. // Use standing matrix if available
  85276. this.getEngine().initWebVRAsync().then(function (result) {
  85277. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85278. callback(false);
  85279. }
  85280. else {
  85281. _this._standingMatrix = new BABYLON.Matrix();
  85282. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85283. if (!_this.getScene().useRightHandedSystem) {
  85284. [2, 6, 8, 9, 14].forEach(function (num) {
  85285. if (_this._standingMatrix) {
  85286. _this._standingMatrix.m[num] *= -1;
  85287. }
  85288. });
  85289. }
  85290. callback(true);
  85291. }
  85292. });
  85293. };
  85294. /**
  85295. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85296. * @returns A promise with a boolean set to if the standing matrix is supported.
  85297. */
  85298. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85299. var _this = this;
  85300. return new Promise(function (res, rej) {
  85301. _this.useStandingMatrix(function (supported) {
  85302. res(supported);
  85303. });
  85304. });
  85305. };
  85306. /**
  85307. * Disposes the camera
  85308. */
  85309. WebVRFreeCamera.prototype.dispose = function () {
  85310. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85311. _super.prototype.dispose.call(this);
  85312. };
  85313. /**
  85314. * Gets a vrController by name.
  85315. * @param name The name of the controller to retreive
  85316. * @returns the controller matching the name specified or null if not found
  85317. */
  85318. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  85319. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  85320. var gp = _a[_i];
  85321. if (gp.hand === name) {
  85322. return gp;
  85323. }
  85324. }
  85325. return null;
  85326. };
  85327. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  85328. /**
  85329. * The controller corrisponding to the users left hand.
  85330. */
  85331. get: function () {
  85332. if (!this._leftController) {
  85333. this._leftController = this.getControllerByName("left");
  85334. }
  85335. return this._leftController;
  85336. },
  85337. enumerable: true,
  85338. configurable: true
  85339. });
  85340. ;
  85341. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  85342. /**
  85343. * The controller corrisponding to the users right hand.
  85344. */
  85345. get: function () {
  85346. if (!this._rightController) {
  85347. this._rightController = this.getControllerByName("right");
  85348. }
  85349. return this._rightController;
  85350. },
  85351. enumerable: true,
  85352. configurable: true
  85353. });
  85354. ;
  85355. /**
  85356. * Casts a ray forward from the vrCamera's gaze.
  85357. * @param length Length of the ray (default: 100)
  85358. * @returns the ray corrisponding to the gaze
  85359. */
  85360. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  85361. if (length === void 0) { length = 100; }
  85362. if (this.leftCamera) {
  85363. // Use left eye to avoid computation to compute center on every call
  85364. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  85365. }
  85366. else {
  85367. return _super.prototype.getForwardRay.call(this, length);
  85368. }
  85369. };
  85370. /**
  85371. * Updates the camera based on device's frame data
  85372. */
  85373. WebVRFreeCamera.prototype._checkInputs = function () {
  85374. if (this._vrDevice && this._vrDevice.isPresenting) {
  85375. this._vrDevice.getFrameData(this._frameData);
  85376. this.updateFromDevice(this._frameData.pose);
  85377. }
  85378. _super.prototype._checkInputs.call(this);
  85379. };
  85380. /**
  85381. * Updates the poseControlled values based on the input device pose.
  85382. * @param poseData Pose coming from the device
  85383. */
  85384. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  85385. if (poseData && poseData.orientation) {
  85386. this.rawPose = poseData;
  85387. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  85388. if (this.getScene().useRightHandedSystem) {
  85389. this._deviceRoomRotationQuaternion.z *= -1;
  85390. this._deviceRoomRotationQuaternion.w *= -1;
  85391. }
  85392. if (this.webVROptions.trackPosition && this.rawPose.position) {
  85393. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  85394. if (this.getScene().useRightHandedSystem) {
  85395. this._deviceRoomPosition.z *= -1;
  85396. }
  85397. }
  85398. }
  85399. };
  85400. /**
  85401. * WebVR's attach control will start broadcasting frames to the device.
  85402. * Note that in certain browsers (chrome for example) this function must be called
  85403. * within a user-interaction callback. Example:
  85404. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  85405. *
  85406. * @param element html element to attach the vrDevice to
  85407. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  85408. */
  85409. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  85410. _super.prototype.attachControl.call(this, element, noPreventDefault);
  85411. this._attached = true;
  85412. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  85413. if (this._vrDevice) {
  85414. this.getEngine().enableVR();
  85415. }
  85416. };
  85417. /**
  85418. * Detaches the camera from the html element and disables VR
  85419. *
  85420. * @param element html element to detach from
  85421. */
  85422. WebVRFreeCamera.prototype.detachControl = function (element) {
  85423. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  85424. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  85425. _super.prototype.detachControl.call(this, element);
  85426. this._attached = false;
  85427. this.getEngine().disableVR();
  85428. };
  85429. /**
  85430. * @returns the name of this class
  85431. */
  85432. WebVRFreeCamera.prototype.getClassName = function () {
  85433. return "WebVRFreeCamera";
  85434. };
  85435. /**
  85436. * Calls resetPose on the vrDisplay
  85437. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  85438. */
  85439. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  85440. //uses the vrDisplay's "resetPose()".
  85441. //pitch and roll won't be affected.
  85442. this._vrDevice.resetPose();
  85443. };
  85444. /**
  85445. * Updates the rig cameras (left and right eye)
  85446. */
  85447. WebVRFreeCamera.prototype._updateRigCameras = function () {
  85448. var camLeft = this._rigCameras[0];
  85449. var camRight = this._rigCameras[1];
  85450. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85451. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85452. camLeft.position.copyFrom(this._deviceRoomPosition);
  85453. camRight.position.copyFrom(this._deviceRoomPosition);
  85454. };
  85455. /**
  85456. * Updates the cached values of the camera
  85457. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  85458. */
  85459. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  85460. var _this = this;
  85461. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  85462. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  85463. if (!this.updateCacheCalled) {
  85464. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  85465. this.updateCacheCalled = true;
  85466. this.update();
  85467. }
  85468. // Set working vector to the device position in room space rotated by the new rotation
  85469. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  85470. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  85471. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  85472. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  85473. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  85474. // Add translation from anchor position
  85475. this._deviceToWorld.getTranslationToRef(this._workingVector);
  85476. this._workingVector.addInPlace(this.position);
  85477. this._workingVector.subtractInPlace(this._cache.position);
  85478. this._deviceToWorld.setTranslation(this._workingVector);
  85479. // Set an inverted matrix to be used when updating the camera
  85480. this._deviceToWorld.invertToRef(this._worldToDevice);
  85481. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  85482. this.controllers.forEach(function (controller) {
  85483. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  85484. controller.update();
  85485. });
  85486. }
  85487. if (!ignoreParentClass) {
  85488. _super.prototype._updateCache.call(this);
  85489. }
  85490. this.updateCacheCalled = false;
  85491. };
  85492. /**
  85493. * Updates the current device position and rotation in the babylon world
  85494. */
  85495. WebVRFreeCamera.prototype.update = function () {
  85496. // Get current device position in babylon world
  85497. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  85498. // Get current device rotation in babylon world
  85499. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  85500. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  85501. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  85502. _super.prototype.update.call(this);
  85503. };
  85504. /**
  85505. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  85506. * @returns an identity matrix
  85507. */
  85508. WebVRFreeCamera.prototype._getViewMatrix = function () {
  85509. return BABYLON.Matrix.Identity();
  85510. };
  85511. /**
  85512. * This function is called by the two RIG cameras.
  85513. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  85514. */
  85515. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  85516. var _this = this;
  85517. // Update the parent camera prior to using a child camera to avoid desynchronization
  85518. var parentCamera = this._cameraRigParams["parentCamera"];
  85519. parentCamera._updateCache();
  85520. //WebVR 1.1
  85521. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  85522. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  85523. if (!this.getScene().useRightHandedSystem) {
  85524. [2, 6, 8, 9, 14].forEach(function (num) {
  85525. _this._webvrViewMatrix.m[num] *= -1;
  85526. });
  85527. }
  85528. // update the camera rotation matrix
  85529. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  85530. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  85531. // Computing target and final matrix
  85532. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  85533. // should the view matrix be updated with scale and position offset?
  85534. if (parentCamera.deviceScaleFactor !== 1) {
  85535. this._webvrViewMatrix.invert();
  85536. // scale the position, if set
  85537. if (parentCamera.deviceScaleFactor) {
  85538. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  85539. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  85540. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  85541. }
  85542. this._webvrViewMatrix.invert();
  85543. }
  85544. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  85545. return this._webvrViewMatrix;
  85546. };
  85547. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  85548. var _this = this;
  85549. var parentCamera = this.parent;
  85550. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  85551. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  85552. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  85553. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  85554. //babylon compatible matrix
  85555. if (!this.getScene().useRightHandedSystem) {
  85556. [8, 9, 10, 11].forEach(function (num) {
  85557. _this._projectionMatrix.m[num] *= -1;
  85558. });
  85559. }
  85560. return this._projectionMatrix;
  85561. };
  85562. /**
  85563. * Initializes the controllers and their meshes
  85564. */
  85565. WebVRFreeCamera.prototype.initControllers = function () {
  85566. var _this = this;
  85567. this.controllers = [];
  85568. var manager = this.getScene().gamepadManager;
  85569. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  85570. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85571. var webVrController = gamepad;
  85572. if (webVrController.defaultModel) {
  85573. webVrController.defaultModel.setEnabled(false);
  85574. }
  85575. if (webVrController.hand === "right") {
  85576. _this._rightController = null;
  85577. }
  85578. if (webVrController.hand === "left") {
  85579. _this._leftController = null;
  85580. }
  85581. var controllerIndex = _this.controllers.indexOf(webVrController);
  85582. if (controllerIndex !== -1) {
  85583. _this.controllers.splice(controllerIndex, 1);
  85584. }
  85585. }
  85586. });
  85587. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  85588. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85589. var webVrController_1 = gamepad;
  85590. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  85591. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  85592. if (_this.webVROptions.controllerMeshes) {
  85593. if (webVrController_1.defaultModel) {
  85594. webVrController_1.defaultModel.setEnabled(true);
  85595. }
  85596. else {
  85597. // Load the meshes
  85598. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85599. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85600. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85601. if (_this.webVROptions.defaultLightingOnControllers) {
  85602. if (!_this._lightOnControllers) {
  85603. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85604. }
  85605. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85606. var children = mesh.getChildren();
  85607. if (children.length !== 0) {
  85608. children.forEach(function (mesh) {
  85609. light.includedOnlyMeshes.push(mesh);
  85610. activateLightOnSubMeshes_1(mesh, light);
  85611. });
  85612. }
  85613. };
  85614. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85615. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85616. }
  85617. });
  85618. }
  85619. }
  85620. webVrController_1.attachToPoseControlledCamera(_this);
  85621. // since this is async - sanity check. Is the controller already stored?
  85622. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85623. //add to the controllers array
  85624. _this.controllers.push(webVrController_1);
  85625. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85626. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85627. // So we're overriding setting left & right manually to be sure
  85628. var firstViveWandDetected = false;
  85629. for (var i = 0; i < _this.controllers.length; i++) {
  85630. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85631. if (!firstViveWandDetected) {
  85632. firstViveWandDetected = true;
  85633. _this.controllers[i].hand = "left";
  85634. }
  85635. else {
  85636. _this.controllers[i].hand = "right";
  85637. }
  85638. }
  85639. }
  85640. //did we find enough controllers? Great! let the developer know.
  85641. if (_this.controllers.length >= 2) {
  85642. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85643. }
  85644. }
  85645. }
  85646. });
  85647. };
  85648. return WebVRFreeCamera;
  85649. }(BABYLON.FreeCamera));
  85650. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85651. })(BABYLON || (BABYLON = {}));
  85652. //# sourceMappingURL=babylon.webVRCamera.js.map
  85653. var BABYLON;
  85654. (function (BABYLON) {
  85655. // We're mainly based on the logic defined into the FreeCamera code
  85656. /**
  85657. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85658. * being tilted forward or back and left or right.
  85659. */
  85660. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85661. __extends(DeviceOrientationCamera, _super);
  85662. /**
  85663. * Creates a new device orientation camera
  85664. * @param name The name of the camera
  85665. * @param position The start position camera
  85666. * @param scene The scene the camera belongs to
  85667. */
  85668. function DeviceOrientationCamera(name, position, scene) {
  85669. var _this = _super.call(this, name, position, scene) || this;
  85670. _this._quaternionCache = new BABYLON.Quaternion();
  85671. _this.inputs.addDeviceOrientation();
  85672. return _this;
  85673. }
  85674. /**
  85675. * Gets the current instance class name ("DeviceOrientationCamera").
  85676. * This helps avoiding instanceof at run time.
  85677. * @returns the class name
  85678. */
  85679. DeviceOrientationCamera.prototype.getClassName = function () {
  85680. return "DeviceOrientationCamera";
  85681. };
  85682. /**
  85683. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85684. */
  85685. DeviceOrientationCamera.prototype._checkInputs = function () {
  85686. _super.prototype._checkInputs.call(this);
  85687. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85688. if (this._initialQuaternion) {
  85689. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85690. }
  85691. };
  85692. /**
  85693. * Reset the camera to its default orientation on the specified axis only.
  85694. * @param axis The axis to reset
  85695. */
  85696. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85697. var _this = this;
  85698. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85699. //can only work if this camera has a rotation quaternion already.
  85700. if (!this.rotationQuaternion)
  85701. return;
  85702. if (!this._initialQuaternion) {
  85703. this._initialQuaternion = new BABYLON.Quaternion();
  85704. }
  85705. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85706. ['x', 'y', 'z'].forEach(function (axisName) {
  85707. if (!axis[axisName]) {
  85708. _this._initialQuaternion[axisName] = 0;
  85709. }
  85710. else {
  85711. _this._initialQuaternion[axisName] *= -1;
  85712. }
  85713. });
  85714. this._initialQuaternion.normalize();
  85715. //force rotation update
  85716. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85717. };
  85718. return DeviceOrientationCamera;
  85719. }(BABYLON.FreeCamera));
  85720. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85721. })(BABYLON || (BABYLON = {}));
  85722. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85723. var BABYLON;
  85724. (function (BABYLON) {
  85725. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85726. __extends(VRDeviceOrientationFreeCamera, _super);
  85727. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85728. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85729. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85730. var _this = _super.call(this, name, position, scene) || this;
  85731. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85732. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85733. return _this;
  85734. }
  85735. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85736. return "VRDeviceOrientationFreeCamera";
  85737. };
  85738. return VRDeviceOrientationFreeCamera;
  85739. }(BABYLON.DeviceOrientationCamera));
  85740. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85741. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85742. __extends(VRDeviceOrientationGamepadCamera, _super);
  85743. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85744. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85745. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85746. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85747. _this.inputs.addGamepad();
  85748. return _this;
  85749. }
  85750. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85751. return "VRDeviceOrientationGamepadCamera";
  85752. };
  85753. return VRDeviceOrientationGamepadCamera;
  85754. }(VRDeviceOrientationFreeCamera));
  85755. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85756. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85757. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85758. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85759. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85760. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85761. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85762. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85763. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85764. _this.inputs.addVRDeviceOrientation();
  85765. return _this;
  85766. }
  85767. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85768. return "VRDeviceOrientationArcRotateCamera";
  85769. };
  85770. return VRDeviceOrientationArcRotateCamera;
  85771. }(BABYLON.ArcRotateCamera));
  85772. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85773. })(BABYLON || (BABYLON = {}));
  85774. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85775. var BABYLON;
  85776. (function (BABYLON) {
  85777. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85778. __extends(AnaglyphFreeCamera, _super);
  85779. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85780. var _this = _super.call(this, name, position, scene) || this;
  85781. _this.interaxialDistance = interaxialDistance;
  85782. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85783. return _this;
  85784. }
  85785. AnaglyphFreeCamera.prototype.getClassName = function () {
  85786. return "AnaglyphFreeCamera";
  85787. };
  85788. return AnaglyphFreeCamera;
  85789. }(BABYLON.FreeCamera));
  85790. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85791. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85792. __extends(AnaglyphArcRotateCamera, _super);
  85793. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85794. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85795. _this.interaxialDistance = interaxialDistance;
  85796. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85797. return _this;
  85798. }
  85799. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85800. return "AnaglyphArcRotateCamera";
  85801. };
  85802. return AnaglyphArcRotateCamera;
  85803. }(BABYLON.ArcRotateCamera));
  85804. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85805. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85806. __extends(AnaglyphGamepadCamera, _super);
  85807. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85808. var _this = _super.call(this, name, position, scene) || this;
  85809. _this.interaxialDistance = interaxialDistance;
  85810. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85811. return _this;
  85812. }
  85813. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85814. return "AnaglyphGamepadCamera";
  85815. };
  85816. return AnaglyphGamepadCamera;
  85817. }(BABYLON.GamepadCamera));
  85818. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85819. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85820. __extends(AnaglyphUniversalCamera, _super);
  85821. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85822. var _this = _super.call(this, name, position, scene) || this;
  85823. _this.interaxialDistance = interaxialDistance;
  85824. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85825. return _this;
  85826. }
  85827. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85828. return "AnaglyphUniversalCamera";
  85829. };
  85830. return AnaglyphUniversalCamera;
  85831. }(BABYLON.UniversalCamera));
  85832. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85833. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85834. __extends(StereoscopicFreeCamera, _super);
  85835. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85836. var _this = _super.call(this, name, position, scene) || this;
  85837. _this.interaxialDistance = interaxialDistance;
  85838. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85839. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85840. return _this;
  85841. }
  85842. StereoscopicFreeCamera.prototype.getClassName = function () {
  85843. return "StereoscopicFreeCamera";
  85844. };
  85845. return StereoscopicFreeCamera;
  85846. }(BABYLON.FreeCamera));
  85847. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85848. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85849. __extends(StereoscopicArcRotateCamera, _super);
  85850. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85851. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85852. _this.interaxialDistance = interaxialDistance;
  85853. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85854. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85855. return _this;
  85856. }
  85857. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85858. return "StereoscopicArcRotateCamera";
  85859. };
  85860. return StereoscopicArcRotateCamera;
  85861. }(BABYLON.ArcRotateCamera));
  85862. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85863. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85864. __extends(StereoscopicGamepadCamera, _super);
  85865. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85866. var _this = _super.call(this, name, position, scene) || this;
  85867. _this.interaxialDistance = interaxialDistance;
  85868. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85869. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85870. return _this;
  85871. }
  85872. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85873. return "StereoscopicGamepadCamera";
  85874. };
  85875. return StereoscopicGamepadCamera;
  85876. }(BABYLON.GamepadCamera));
  85877. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85878. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85879. __extends(StereoscopicUniversalCamera, _super);
  85880. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85881. var _this = _super.call(this, name, position, scene) || this;
  85882. _this.interaxialDistance = interaxialDistance;
  85883. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85884. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85885. return _this;
  85886. }
  85887. StereoscopicUniversalCamera.prototype.getClassName = function () {
  85888. return "StereoscopicUniversalCamera";
  85889. };
  85890. return StereoscopicUniversalCamera;
  85891. }(BABYLON.UniversalCamera));
  85892. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  85893. })(BABYLON || (BABYLON = {}));
  85894. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  85895. var BABYLON;
  85896. (function (BABYLON) {
  85897. var VRExperienceHelperGazer = /** @class */ (function () {
  85898. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  85899. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  85900. this.scene = scene;
  85901. this._pointerDownOnMeshAsked = false;
  85902. this._isActionableMesh = false;
  85903. this._teleportationRequestInitiated = false;
  85904. this._teleportationBackRequestInitiated = false;
  85905. this._dpadPressed = true;
  85906. this._activePointer = false;
  85907. this._id = VRExperienceHelperGazer._idCounter++;
  85908. // Gaze tracker
  85909. if (!gazeTrackerToClone) {
  85910. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  85911. this._gazeTracker.bakeCurrentTransformIntoVertices();
  85912. this._gazeTracker.isPickable = false;
  85913. this._gazeTracker.isVisible = false;
  85914. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  85915. targetMat.specularColor = BABYLON.Color3.Black();
  85916. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85917. targetMat.backFaceCulling = false;
  85918. this._gazeTracker.material = targetMat;
  85919. }
  85920. else {
  85921. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  85922. }
  85923. }
  85924. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  85925. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  85926. };
  85927. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  85928. this._pointerDownOnMeshAsked = true;
  85929. if (this._currentMeshSelected && this._currentHit) {
  85930. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  85931. }
  85932. };
  85933. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  85934. if (this._currentMeshSelected && this._currentHit) {
  85935. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  85936. }
  85937. this._pointerDownOnMeshAsked = false;
  85938. };
  85939. VRExperienceHelperGazer.prototype._activatePointer = function () {
  85940. this._activePointer = true;
  85941. };
  85942. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  85943. this._activePointer = false;
  85944. };
  85945. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  85946. };
  85947. VRExperienceHelperGazer.prototype.dispose = function () {
  85948. this._interactionsEnabled = false;
  85949. this._teleportationEnabled = false;
  85950. };
  85951. VRExperienceHelperGazer._idCounter = 0;
  85952. return VRExperienceHelperGazer;
  85953. }());
  85954. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  85955. __extends(VRExperienceHelperControllerGazer, _super);
  85956. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  85957. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  85958. _this.webVRController = webVRController;
  85959. // Laser pointer
  85960. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  85961. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  85962. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85963. laserPointerMaterial.alpha = 0.6;
  85964. _this._laserPointer.material = laserPointerMaterial;
  85965. _this._laserPointer.rotation.x = Math.PI / 2;
  85966. _this._laserPointer.position.z = -0.5;
  85967. _this._laserPointer.isVisible = false;
  85968. if (!webVRController.mesh) {
  85969. // Create an empty mesh that is used prior to loading the high quality model
  85970. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  85971. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  85972. preloadPointerPose.rotation.x = -0.7;
  85973. preloadMesh.addChild(preloadPointerPose);
  85974. webVRController.attachToMesh(preloadMesh);
  85975. }
  85976. _this._setLaserPointerParent(webVRController.mesh);
  85977. return _this;
  85978. }
  85979. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  85980. return this.webVRController.getForwardRay(length);
  85981. };
  85982. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  85983. _super.prototype._activatePointer.call(this);
  85984. this._laserPointer.isVisible = true;
  85985. };
  85986. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  85987. _super.prototype._deactivatePointer.call(this);
  85988. this._laserPointer.isVisible = false;
  85989. };
  85990. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  85991. this._laserPointer.material.emissiveColor = color;
  85992. };
  85993. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  85994. var makeNotPick = function (root) {
  85995. root.name += " laserPointer";
  85996. root.getChildMeshes().forEach(function (c) {
  85997. makeNotPick(c);
  85998. });
  85999. };
  86000. makeNotPick(mesh);
  86001. var childMeshes = mesh.getChildMeshes();
  86002. this.webVRController._pointingPoseNode = null;
  86003. for (var i = 0; i < childMeshes.length; i++) {
  86004. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86005. mesh = childMeshes[i];
  86006. this.webVRController._pointingPoseNode = mesh;
  86007. break;
  86008. }
  86009. }
  86010. this._laserPointer.parent = mesh;
  86011. };
  86012. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86013. this._laserPointer.scaling.y = distance;
  86014. this._laserPointer.position.z = -distance / 2;
  86015. };
  86016. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86017. _super.prototype.dispose.call(this);
  86018. this._laserPointer.dispose();
  86019. };
  86020. return VRExperienceHelperControllerGazer;
  86021. }(VRExperienceHelperGazer));
  86022. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86023. __extends(VRExperienceHelperCameraGazer, _super);
  86024. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86025. var _this = _super.call(this, scene) || this;
  86026. _this.getCamera = getCamera;
  86027. return _this;
  86028. }
  86029. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86030. var camera = this.getCamera();
  86031. if (camera) {
  86032. return camera.getForwardRay(length);
  86033. }
  86034. else {
  86035. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86036. }
  86037. };
  86038. return VRExperienceHelperCameraGazer;
  86039. }(VRExperienceHelperGazer));
  86040. /**
  86041. * Helps to quickly add VR support to an existing scene.
  86042. * See http://doc.babylonjs.com/how_to/webvr_helper
  86043. */
  86044. var VRExperienceHelper = /** @class */ (function () {
  86045. /**
  86046. * Instantiates a VRExperienceHelper.
  86047. * Helps to quickly add VR support to an existing scene.
  86048. * @param scene The scene the VRExperienceHelper belongs to.
  86049. * @param webVROptions Options to modify the vr experience helper's behavior.
  86050. */
  86051. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86052. if (webVROptions === void 0) { webVROptions = {}; }
  86053. var _this = this;
  86054. this.webVROptions = webVROptions;
  86055. // Can the system support WebVR, even if a headset isn't plugged in?
  86056. this._webVRsupported = false;
  86057. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86058. this._webVRready = false;
  86059. // Are we waiting for the requestPresent callback to complete?
  86060. this._webVRrequesting = false;
  86061. // Are we presenting to the headset right now?
  86062. this._webVRpresenting = false;
  86063. // Are we presenting in the fullscreen fallback?
  86064. this._fullscreenVRpresenting = false;
  86065. /**
  86066. * Observable raised when entering VR.
  86067. */
  86068. this.onEnteringVRObservable = new BABYLON.Observable();
  86069. /**
  86070. * Observable raised when exiting VR.
  86071. */
  86072. this.onExitingVRObservable = new BABYLON.Observable();
  86073. /**
  86074. * Observable raised when controller mesh is loaded.
  86075. */
  86076. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86077. this._useCustomVRButton = false;
  86078. this._teleportationRequested = false;
  86079. this._teleportActive = false;
  86080. this._floorMeshesCollection = [];
  86081. this._rotationAllowed = true;
  86082. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86083. this._rotationRightAsked = false;
  86084. this._rotationLeftAsked = false;
  86085. this._isDefaultTeleportationTarget = true;
  86086. this._teleportationFillColor = "#444444";
  86087. this._teleportationBorderColor = "#FFFFFF";
  86088. this._rotationAngle = 0;
  86089. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86090. this._padSensibilityUp = 0.65;
  86091. this._padSensibilityDown = 0.35;
  86092. this.leftController = null;
  86093. this.rightController = null;
  86094. /**
  86095. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86096. */
  86097. this.onNewMeshSelected = new BABYLON.Observable();
  86098. /**
  86099. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86100. */
  86101. this.onNewMeshPicked = new BABYLON.Observable();
  86102. /**
  86103. * Observable raised before camera teleportation
  86104. */
  86105. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86106. /**
  86107. * Observable raised after camera teleportation
  86108. */
  86109. this.onAfterCameraTeleport = new BABYLON.Observable();
  86110. /**
  86111. * Observable raised when current selected mesh gets unselected
  86112. */
  86113. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86114. /**
  86115. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86116. */
  86117. this.teleportationEnabled = true;
  86118. this._teleportationInitialized = false;
  86119. this._interactionsEnabled = false;
  86120. this._interactionsRequested = false;
  86121. this._displayGaze = true;
  86122. this._displayLaserPointer = true;
  86123. this._onResize = function () {
  86124. _this.moveButtonToBottomRight();
  86125. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86126. _this.exitVR();
  86127. }
  86128. };
  86129. this._onFullscreenChange = function () {
  86130. if (document.fullscreen !== undefined) {
  86131. _this._fullscreenVRpresenting = document.fullscreen;
  86132. }
  86133. else if (document.mozFullScreen !== undefined) {
  86134. _this._fullscreenVRpresenting = document.mozFullScreen;
  86135. }
  86136. else if (document.webkitIsFullScreen !== undefined) {
  86137. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86138. }
  86139. else if (document.msIsFullScreen !== undefined) {
  86140. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86141. }
  86142. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86143. _this.exitVR();
  86144. if (!_this._useCustomVRButton) {
  86145. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86146. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86147. }
  86148. }
  86149. };
  86150. this.beforeRender = function () {
  86151. if (_this.leftController && _this.leftController._activePointer) {
  86152. _this._castRayAndSelectObject(_this.leftController);
  86153. }
  86154. if (_this.rightController && _this.rightController._activePointer) {
  86155. _this._castRayAndSelectObject(_this.rightController);
  86156. }
  86157. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86158. _this._castRayAndSelectObject(_this._cameraGazer);
  86159. }
  86160. else {
  86161. _this._cameraGazer._gazeTracker.isVisible = false;
  86162. }
  86163. };
  86164. this._onNewGamepadConnected = function (gamepad) {
  86165. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86166. if (gamepad.leftStick) {
  86167. gamepad.onleftstickchanged(function (stickValues) {
  86168. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86169. // Listening to classic/xbox gamepad only if no VR controller is active
  86170. if ((!_this.leftController && !_this.rightController) ||
  86171. ((_this.leftController && !_this.leftController._activePointer) &&
  86172. (_this.rightController && !_this.rightController._activePointer))) {
  86173. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86174. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86175. }
  86176. }
  86177. });
  86178. }
  86179. if (gamepad.rightStick) {
  86180. gamepad.onrightstickchanged(function (stickValues) {
  86181. if (_this._teleportationInitialized) {
  86182. _this._checkRotate(stickValues, _this._cameraGazer);
  86183. }
  86184. });
  86185. }
  86186. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86187. gamepad.onbuttondown(function (buttonPressed) {
  86188. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86189. _this._cameraGazer._selectionPointerDown();
  86190. }
  86191. });
  86192. gamepad.onbuttonup(function (buttonPressed) {
  86193. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86194. _this._cameraGazer._selectionPointerUp();
  86195. }
  86196. });
  86197. }
  86198. }
  86199. else {
  86200. var webVRController = gamepad;
  86201. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86202. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86203. _this.rightController = controller;
  86204. }
  86205. else {
  86206. _this.leftController = controller;
  86207. }
  86208. _this._tryEnableInteractionOnController(controller);
  86209. }
  86210. };
  86211. // 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
  86212. this._tryEnableInteractionOnController = function (controller) {
  86213. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86214. _this._enableInteractionOnController(controller);
  86215. }
  86216. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86217. _this._enableTeleportationOnController(controller);
  86218. }
  86219. };
  86220. this._onNewGamepadDisconnected = function (gamepad) {
  86221. if (gamepad instanceof BABYLON.WebVRController) {
  86222. if (gamepad.hand === "left" && _this.leftController != null) {
  86223. _this.leftController.dispose();
  86224. _this.leftController = null;
  86225. }
  86226. if (gamepad.hand === "right" && _this.rightController != null) {
  86227. _this.rightController.dispose();
  86228. _this.rightController = null;
  86229. }
  86230. }
  86231. };
  86232. this._workingVector = BABYLON.Vector3.Zero();
  86233. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86234. this._workingMatrix = BABYLON.Matrix.Identity();
  86235. this._scene = scene;
  86236. this._canvas = scene.getEngine().getRenderingCanvas();
  86237. // Parse options
  86238. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86239. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86240. }
  86241. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86242. webVROptions.createDeviceOrientationCamera = true;
  86243. }
  86244. if (webVROptions.defaultHeight === undefined) {
  86245. webVROptions.defaultHeight = 1.7;
  86246. }
  86247. if (webVROptions.useCustomVRButton) {
  86248. this._useCustomVRButton = true;
  86249. if (webVROptions.customVRButton) {
  86250. this._btnVR = webVROptions.customVRButton;
  86251. }
  86252. }
  86253. if (webVROptions.rayLength) {
  86254. this._rayLength = webVROptions.rayLength;
  86255. }
  86256. this._defaultHeight = webVROptions.defaultHeight;
  86257. if (webVROptions.positionScale) {
  86258. this._rayLength *= webVROptions.positionScale;
  86259. this._defaultHeight *= webVROptions.positionScale;
  86260. }
  86261. // Set position
  86262. if (this._scene.activeCamera) {
  86263. this._position = this._scene.activeCamera.position.clone();
  86264. }
  86265. else {
  86266. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86267. }
  86268. // Set non-vr camera
  86269. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86270. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86271. // Copy data from existing camera
  86272. if (this._scene.activeCamera) {
  86273. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86274. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86275. // Set rotation from previous camera
  86276. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86277. var targetCamera = this._scene.activeCamera;
  86278. if (targetCamera.rotationQuaternion) {
  86279. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86280. }
  86281. else {
  86282. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86283. }
  86284. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86285. }
  86286. }
  86287. this._scene.activeCamera = this._deviceOrientationCamera;
  86288. if (this._canvas) {
  86289. this._scene.activeCamera.attachControl(this._canvas);
  86290. }
  86291. }
  86292. else {
  86293. this._existingCamera = this._scene.activeCamera;
  86294. }
  86295. // Create VR cameras
  86296. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86297. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86298. }
  86299. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86300. this._webVRCamera.useStandingMatrix();
  86301. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86302. // Create default button
  86303. if (!this._useCustomVRButton) {
  86304. this._btnVR = document.createElement("BUTTON");
  86305. this._btnVR.className = "babylonVRicon";
  86306. this._btnVR.id = "babylonVRiconbtn";
  86307. this._btnVR.title = "Click to switch to VR";
  86308. 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) }";
  86309. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86310. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86311. // css += ".babylonVRicon.vrdisplaysupported { }";
  86312. // css += ".babylonVRicon.vrdisplayready { }";
  86313. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86314. var style = document.createElement('style');
  86315. style.appendChild(document.createTextNode(css));
  86316. document.getElementsByTagName('head')[0].appendChild(style);
  86317. this.moveButtonToBottomRight();
  86318. }
  86319. // VR button click event
  86320. if (this._btnVR) {
  86321. this._btnVR.addEventListener("click", function () {
  86322. if (!_this.isInVRMode) {
  86323. _this.enterVR();
  86324. }
  86325. else {
  86326. _this.exitVR();
  86327. }
  86328. });
  86329. }
  86330. // Window events
  86331. window.addEventListener("resize", this._onResize);
  86332. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  86333. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  86334. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  86335. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  86336. // Display vr button when headset is connected
  86337. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86338. this.displayVRButton();
  86339. }
  86340. else {
  86341. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  86342. if (e.vrDisplay) {
  86343. _this.displayVRButton();
  86344. }
  86345. });
  86346. }
  86347. // Exiting VR mode using 'ESC' key on desktop
  86348. this._onKeyDown = function (event) {
  86349. if (event.keyCode === 27 && _this.isInVRMode) {
  86350. _this.exitVR();
  86351. }
  86352. };
  86353. document.addEventListener("keydown", this._onKeyDown);
  86354. // Exiting VR mode double tapping the touch screen
  86355. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  86356. if (_this.isInVRMode) {
  86357. _this.exitVR();
  86358. if (_this._fullscreenVRpresenting) {
  86359. _this._scene.getEngine().switchFullscreen(true);
  86360. }
  86361. }
  86362. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  86363. // Listen for WebVR display changes
  86364. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  86365. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  86366. this._onVRRequestPresentStart = function () {
  86367. _this._webVRrequesting = true;
  86368. _this.updateButtonVisibility();
  86369. };
  86370. this._onVRRequestPresentComplete = function (success) {
  86371. _this._webVRrequesting = false;
  86372. _this.updateButtonVisibility();
  86373. };
  86374. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  86375. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  86376. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  86377. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86378. scene.onDisposeObservable.add(function () {
  86379. _this.dispose();
  86380. });
  86381. // Gamepad connection events
  86382. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  86383. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  86384. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  86385. this.updateButtonVisibility();
  86386. //create easing functions
  86387. this._circleEase = new BABYLON.CircleEase();
  86388. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86389. }
  86390. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  86391. /** Return this.onEnteringVRObservable
  86392. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  86393. */
  86394. get: function () {
  86395. return this.onEnteringVRObservable;
  86396. },
  86397. enumerable: true,
  86398. configurable: true
  86399. });
  86400. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  86401. /** Return this.onExitingVRObservable
  86402. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  86403. */
  86404. get: function () {
  86405. return this.onExitingVRObservable;
  86406. },
  86407. enumerable: true,
  86408. configurable: true
  86409. });
  86410. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  86411. /** Return this.onControllerMeshLoadedObservable
  86412. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  86413. */
  86414. get: function () {
  86415. return this.onControllerMeshLoadedObservable;
  86416. },
  86417. enumerable: true,
  86418. configurable: true
  86419. });
  86420. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  86421. /**
  86422. * The mesh used to display where the user is going to teleport.
  86423. */
  86424. get: function () {
  86425. return this._teleportationTarget;
  86426. },
  86427. /**
  86428. * Sets the mesh to be used to display where the user is going to teleport.
  86429. */
  86430. set: function (value) {
  86431. if (value) {
  86432. value.name = "teleportationTarget";
  86433. this._isDefaultTeleportationTarget = false;
  86434. this._teleportationTarget = value;
  86435. }
  86436. },
  86437. enumerable: true,
  86438. configurable: true
  86439. });
  86440. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  86441. /**
  86442. * The mesh used to display where the user is selecting,
  86443. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  86444. * See http://doc.babylonjs.com/resources/baking_transformations
  86445. */
  86446. get: function () {
  86447. return this._cameraGazer._gazeTracker;
  86448. },
  86449. set: function (value) {
  86450. if (value) {
  86451. this._cameraGazer._gazeTracker = value;
  86452. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  86453. this._cameraGazer._gazeTracker.isPickable = false;
  86454. this._cameraGazer._gazeTracker.isVisible = false;
  86455. this._cameraGazer._gazeTracker.name = "gazeTracker";
  86456. if (this.leftController) {
  86457. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86458. }
  86459. if (this.rightController) {
  86460. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86461. }
  86462. }
  86463. },
  86464. enumerable: true,
  86465. configurable: true
  86466. });
  86467. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  86468. /**
  86469. * If the ray of the gaze should be displayed.
  86470. */
  86471. get: function () {
  86472. return this._displayGaze;
  86473. },
  86474. /**
  86475. * Sets if the ray of the gaze should be displayed.
  86476. */
  86477. set: function (value) {
  86478. this._displayGaze = value;
  86479. if (!value) {
  86480. this._cameraGazer._gazeTracker.isVisible = false;
  86481. if (this.leftController) {
  86482. this.leftController._gazeTracker.isVisible = false;
  86483. }
  86484. if (this.rightController) {
  86485. this.rightController._gazeTracker.isVisible = false;
  86486. }
  86487. }
  86488. },
  86489. enumerable: true,
  86490. configurable: true
  86491. });
  86492. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  86493. /**
  86494. * If the ray of the LaserPointer should be displayed.
  86495. */
  86496. get: function () {
  86497. return this._displayLaserPointer;
  86498. },
  86499. /**
  86500. * Sets if the ray of the LaserPointer should be displayed.
  86501. */
  86502. set: function (value) {
  86503. this._displayLaserPointer = value;
  86504. if (!value) {
  86505. if (this.rightController) {
  86506. this.rightController._deactivatePointer();
  86507. this.rightController._gazeTracker.isVisible = false;
  86508. }
  86509. if (this.leftController) {
  86510. this.leftController._deactivatePointer();
  86511. this.leftController._gazeTracker.isVisible = false;
  86512. }
  86513. }
  86514. else {
  86515. if (this.rightController) {
  86516. this.rightController._activatePointer();
  86517. }
  86518. else if (this.leftController) {
  86519. this.leftController._activatePointer();
  86520. }
  86521. }
  86522. },
  86523. enumerable: true,
  86524. configurable: true
  86525. });
  86526. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  86527. /**
  86528. * The deviceOrientationCamera used as the camera when not in VR.
  86529. */
  86530. get: function () {
  86531. return this._deviceOrientationCamera;
  86532. },
  86533. enumerable: true,
  86534. configurable: true
  86535. });
  86536. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  86537. /**
  86538. * Based on the current WebVR support, returns the current VR camera used.
  86539. */
  86540. get: function () {
  86541. if (this._webVRready) {
  86542. return this._webVRCamera;
  86543. }
  86544. else {
  86545. return this._scene.activeCamera;
  86546. }
  86547. },
  86548. enumerable: true,
  86549. configurable: true
  86550. });
  86551. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  86552. /**
  86553. * The webVRCamera which is used when in VR.
  86554. */
  86555. get: function () {
  86556. return this._webVRCamera;
  86557. },
  86558. enumerable: true,
  86559. configurable: true
  86560. });
  86561. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  86562. /**
  86563. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  86564. */
  86565. get: function () {
  86566. return this._vrDeviceOrientationCamera;
  86567. },
  86568. enumerable: true,
  86569. configurable: true
  86570. });
  86571. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  86572. get: function () {
  86573. var result = this._cameraGazer._teleportationRequestInitiated
  86574. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  86575. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  86576. return result;
  86577. },
  86578. enumerable: true,
  86579. configurable: true
  86580. });
  86581. // Raised when one of the controller has loaded successfully its associated default mesh
  86582. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  86583. if (this.leftController && this.leftController.webVRController == webVRController) {
  86584. if (webVRController.mesh) {
  86585. this.leftController._setLaserPointerParent(webVRController.mesh);
  86586. }
  86587. }
  86588. if (this.rightController && this.rightController.webVRController == webVRController) {
  86589. if (webVRController.mesh) {
  86590. this.rightController._setLaserPointerParent(webVRController.mesh);
  86591. }
  86592. }
  86593. try {
  86594. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86595. }
  86596. catch (err) {
  86597. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86598. }
  86599. };
  86600. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86601. /**
  86602. * Gets a value indicating if we are currently in VR mode.
  86603. */
  86604. get: function () {
  86605. return this._webVRpresenting || this._fullscreenVRpresenting;
  86606. },
  86607. enumerable: true,
  86608. configurable: true
  86609. });
  86610. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86611. var vrDisplay = this._scene.getEngine().getVRDevice();
  86612. if (vrDisplay) {
  86613. var wasPresenting = this._webVRpresenting;
  86614. // A VR display is connected
  86615. this._webVRpresenting = vrDisplay.isPresenting;
  86616. if (wasPresenting && !this._webVRpresenting)
  86617. this.exitVR();
  86618. }
  86619. else {
  86620. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86621. }
  86622. this.updateButtonVisibility();
  86623. };
  86624. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86625. this._webVRsupported = eventArgs.vrSupported;
  86626. this._webVRready = !!eventArgs.vrDisplay;
  86627. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86628. this.updateButtonVisibility();
  86629. };
  86630. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86631. if (this._canvas && !this._useCustomVRButton) {
  86632. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86633. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86634. }
  86635. };
  86636. VRExperienceHelper.prototype.displayVRButton = function () {
  86637. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86638. document.body.appendChild(this._btnVR);
  86639. this._btnVRDisplayed = true;
  86640. }
  86641. };
  86642. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86643. if (!this._btnVR || this._useCustomVRButton) {
  86644. return;
  86645. }
  86646. this._btnVR.className = "babylonVRicon";
  86647. if (this.isInVRMode) {
  86648. this._btnVR.className += " vrdisplaypresenting";
  86649. }
  86650. else {
  86651. if (this._webVRready)
  86652. this._btnVR.className += " vrdisplayready";
  86653. if (this._webVRsupported)
  86654. this._btnVR.className += " vrdisplaysupported";
  86655. if (this._webVRrequesting)
  86656. this._btnVR.className += " vrdisplayrequesting";
  86657. }
  86658. };
  86659. /**
  86660. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86661. * Otherwise, will use the fullscreen API.
  86662. */
  86663. VRExperienceHelper.prototype.enterVR = function () {
  86664. if (this.onEnteringVRObservable) {
  86665. try {
  86666. this.onEnteringVRObservable.notifyObservers(this);
  86667. }
  86668. catch (err) {
  86669. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86670. }
  86671. }
  86672. if (this._scene.activeCamera) {
  86673. this._position = this._scene.activeCamera.position.clone();
  86674. // make sure that we return to the last active camera
  86675. this._existingCamera = this._scene.activeCamera;
  86676. }
  86677. if (this._webVRrequesting)
  86678. return;
  86679. // If WebVR is supported and a headset is connected
  86680. if (this._webVRready) {
  86681. if (!this._webVRpresenting) {
  86682. this._webVRCamera.position = this._position;
  86683. this._scene.activeCamera = this._webVRCamera;
  86684. }
  86685. }
  86686. else if (this._vrDeviceOrientationCamera) {
  86687. this._vrDeviceOrientationCamera.position = this._position;
  86688. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86689. this._scene.getEngine().switchFullscreen(true);
  86690. this.updateButtonVisibility();
  86691. }
  86692. if (this._scene.activeCamera && this._canvas) {
  86693. this._scene.activeCamera.attachControl(this._canvas);
  86694. }
  86695. if (this._interactionsEnabled) {
  86696. this._scene.registerBeforeRender(this.beforeRender);
  86697. }
  86698. };
  86699. /**
  86700. * Attempt to exit VR, or fullscreen.
  86701. */
  86702. VRExperienceHelper.prototype.exitVR = function () {
  86703. if (this.onExitingVRObservable) {
  86704. try {
  86705. this.onExitingVRObservable.notifyObservers(this);
  86706. }
  86707. catch (err) {
  86708. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86709. }
  86710. }
  86711. if (this._webVRpresenting) {
  86712. this._scene.getEngine().disableVR();
  86713. }
  86714. if (this._scene.activeCamera) {
  86715. this._position = this._scene.activeCamera.position.clone();
  86716. }
  86717. if (this._deviceOrientationCamera) {
  86718. this._deviceOrientationCamera.position = this._position;
  86719. this._scene.activeCamera = this._deviceOrientationCamera;
  86720. if (this._canvas) {
  86721. this._scene.activeCamera.attachControl(this._canvas);
  86722. }
  86723. }
  86724. else if (this._existingCamera) {
  86725. this._existingCamera.position = this._position;
  86726. this._scene.activeCamera = this._existingCamera;
  86727. }
  86728. this.updateButtonVisibility();
  86729. if (this._interactionsEnabled) {
  86730. this._scene.unregisterBeforeRender(this.beforeRender);
  86731. }
  86732. };
  86733. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86734. /**
  86735. * The position of the vr experience helper.
  86736. */
  86737. get: function () {
  86738. return this._position;
  86739. },
  86740. /**
  86741. * Sets the position of the vr experience helper.
  86742. */
  86743. set: function (value) {
  86744. this._position = value;
  86745. if (this._scene.activeCamera) {
  86746. this._scene.activeCamera.position = value;
  86747. }
  86748. },
  86749. enumerable: true,
  86750. configurable: true
  86751. });
  86752. /**
  86753. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86754. */
  86755. VRExperienceHelper.prototype.enableInteractions = function () {
  86756. var _this = this;
  86757. if (!this._interactionsEnabled) {
  86758. this._interactionsRequested = true;
  86759. if (this.leftController) {
  86760. this._enableInteractionOnController(this.leftController);
  86761. }
  86762. if (this.rightController) {
  86763. this._enableInteractionOnController(this.rightController);
  86764. }
  86765. this.raySelectionPredicate = function (mesh) {
  86766. return mesh.isVisible;
  86767. };
  86768. this.meshSelectionPredicate = function (mesh) {
  86769. return true;
  86770. };
  86771. this._raySelectionPredicate = function (mesh) {
  86772. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86773. && mesh.name.indexOf("teleportationTarget") === -1
  86774. && mesh.name.indexOf("torusTeleportation") === -1
  86775. && mesh.name.indexOf("laserPointer") === -1)) {
  86776. return _this.raySelectionPredicate(mesh);
  86777. }
  86778. return false;
  86779. };
  86780. this._interactionsEnabled = true;
  86781. }
  86782. };
  86783. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86784. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86785. if (this._floorMeshesCollection[i].id === mesh.id) {
  86786. return true;
  86787. }
  86788. }
  86789. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86790. return true;
  86791. }
  86792. return false;
  86793. };
  86794. /**
  86795. * Adds a floor mesh to be used for teleportation.
  86796. * @param floorMesh the mesh to be used for teleportation.
  86797. */
  86798. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86799. if (!this._floorMeshesCollection) {
  86800. return;
  86801. }
  86802. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86803. return;
  86804. }
  86805. this._floorMeshesCollection.push(floorMesh);
  86806. };
  86807. /**
  86808. * Removes a floor mesh from being used for teleportation.
  86809. * @param floorMesh the mesh to be removed.
  86810. */
  86811. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86812. if (!this._floorMeshesCollection) {
  86813. return;
  86814. }
  86815. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86816. if (meshIndex !== -1) {
  86817. this._floorMeshesCollection.splice(meshIndex, 1);
  86818. }
  86819. };
  86820. /**
  86821. * Enables interactions and teleportation using the VR controllers and gaze.
  86822. * @param vrTeleportationOptions options to modify teleportation behavior.
  86823. */
  86824. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86825. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86826. if (!this._teleportationInitialized) {
  86827. this._teleportationRequested = true;
  86828. this.enableInteractions();
  86829. if (vrTeleportationOptions.floorMeshName) {
  86830. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86831. }
  86832. if (vrTeleportationOptions.floorMeshes) {
  86833. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86834. }
  86835. if (this.leftController != null) {
  86836. this._enableTeleportationOnController(this.leftController);
  86837. }
  86838. if (this.rightController != null) {
  86839. this._enableTeleportationOnController(this.rightController);
  86840. }
  86841. // Creates an image processing post process for the vignette not relying
  86842. // on the main scene configuration for image processing to reduce setup and spaces
  86843. // (gamma/linear) conflicts.
  86844. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86845. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86846. imageProcessingConfiguration.vignetteEnabled = true;
  86847. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86848. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86849. this._teleportationInitialized = true;
  86850. if (this._isDefaultTeleportationTarget) {
  86851. this._createTeleportationCircles();
  86852. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86853. }
  86854. }
  86855. };
  86856. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86857. var _this = this;
  86858. var controllerMesh = controller.webVRController.mesh;
  86859. if (controllerMesh) {
  86860. controller._interactionsEnabled = true;
  86861. controller._activatePointer();
  86862. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86863. // Enabling / disabling laserPointer
  86864. if (_this._displayLaserPointer && stateObject.value === 1) {
  86865. if (controller._activePointer) {
  86866. controller._deactivatePointer();
  86867. }
  86868. else {
  86869. controller._activatePointer();
  86870. }
  86871. if (_this.displayGaze) {
  86872. controller._gazeTracker.isVisible = controller._activePointer;
  86873. }
  86874. }
  86875. });
  86876. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86877. if (!controller._pointerDownOnMeshAsked) {
  86878. if (stateObject.value > _this._padSensibilityUp) {
  86879. controller._selectionPointerDown();
  86880. }
  86881. }
  86882. else if (stateObject.value < _this._padSensibilityDown) {
  86883. controller._selectionPointerUp();
  86884. }
  86885. });
  86886. }
  86887. };
  86888. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  86889. // Dont teleport if another gaze already requested teleportation
  86890. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  86891. return;
  86892. }
  86893. if (!gazer._teleportationRequestInitiated) {
  86894. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  86895. gazer._activatePointer();
  86896. gazer._teleportationRequestInitiated = true;
  86897. }
  86898. }
  86899. else {
  86900. // Listening to the proper controller values changes to confirm teleportation
  86901. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  86902. if (this._teleportActive) {
  86903. this._teleportCamera(this._haloCenter);
  86904. }
  86905. gazer._teleportationRequestInitiated = false;
  86906. }
  86907. }
  86908. };
  86909. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  86910. // Only rotate when user is not currently selecting a teleportation location
  86911. if (gazer._teleportationRequestInitiated) {
  86912. return;
  86913. }
  86914. if (!this._rotationLeftAsked) {
  86915. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  86916. this._rotationLeftAsked = true;
  86917. if (this._rotationAllowed) {
  86918. this._rotateCamera(false);
  86919. }
  86920. }
  86921. }
  86922. else {
  86923. if (stateObject.x > -this._padSensibilityDown) {
  86924. this._rotationLeftAsked = false;
  86925. }
  86926. }
  86927. if (!this._rotationRightAsked) {
  86928. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  86929. this._rotationRightAsked = true;
  86930. if (this._rotationAllowed) {
  86931. this._rotateCamera(true);
  86932. }
  86933. }
  86934. }
  86935. else {
  86936. if (stateObject.x < this._padSensibilityDown) {
  86937. this._rotationRightAsked = false;
  86938. }
  86939. }
  86940. };
  86941. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  86942. // Only teleport backwards when user is not currently selecting a teleportation location
  86943. if (gazer._teleportationRequestInitiated) {
  86944. return;
  86945. }
  86946. // Teleport backwards
  86947. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  86948. if (!gazer._teleportationBackRequestInitiated) {
  86949. if (!this.currentVRCamera) {
  86950. return;
  86951. }
  86952. // Get rotation and position of the current camera
  86953. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  86954. var position = this.currentVRCamera.position;
  86955. // If the camera has device position, use that instead
  86956. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  86957. rotation = this.currentVRCamera.deviceRotationQuaternion;
  86958. position = this.currentVRCamera.devicePosition;
  86959. }
  86960. // Get matrix with only the y rotation of the device rotation
  86961. rotation.toEulerAnglesToRef(this._workingVector);
  86962. this._workingVector.z = 0;
  86963. this._workingVector.x = 0;
  86964. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  86965. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  86966. // Rotate backwards ray by device rotation to cast at the ground behind the user
  86967. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  86968. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  86969. var ray = new BABYLON.Ray(position, this._workingVector);
  86970. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  86971. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  86972. this._teleportCamera(hit.pickedPoint);
  86973. }
  86974. gazer._teleportationBackRequestInitiated = true;
  86975. }
  86976. }
  86977. else {
  86978. gazer._teleportationBackRequestInitiated = false;
  86979. }
  86980. };
  86981. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  86982. var _this = this;
  86983. var controllerMesh = controller.webVRController.mesh;
  86984. if (controllerMesh) {
  86985. if (!controller._interactionsEnabled) {
  86986. this._enableInteractionOnController(controller);
  86987. }
  86988. controller._interactionsEnabled = true;
  86989. controller._teleportationEnabled = true;
  86990. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86991. controller._dpadPressed = false;
  86992. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  86993. controller._dpadPressed = stateObject.pressed;
  86994. if (!controller._dpadPressed) {
  86995. _this._rotationLeftAsked = false;
  86996. _this._rotationRightAsked = false;
  86997. controller._teleportationBackRequestInitiated = false;
  86998. }
  86999. });
  87000. }
  87001. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87002. if (_this.teleportationEnabled) {
  87003. _this._checkTeleportBackwards(stateObject, controller);
  87004. _this._checkTeleportWithRay(stateObject, controller);
  87005. }
  87006. _this._checkRotate(stateObject, controller);
  87007. });
  87008. }
  87009. };
  87010. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87011. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87012. this._teleportationTarget.isPickable = false;
  87013. var length = 512;
  87014. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87015. dynamicTexture.hasAlpha = true;
  87016. var context = dynamicTexture.getContext();
  87017. var centerX = length / 2;
  87018. var centerY = length / 2;
  87019. var radius = 200;
  87020. context.beginPath();
  87021. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87022. context.fillStyle = this._teleportationFillColor;
  87023. context.fill();
  87024. context.lineWidth = 10;
  87025. context.strokeStyle = this._teleportationBorderColor;
  87026. context.stroke();
  87027. context.closePath();
  87028. dynamicTexture.update();
  87029. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87030. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87031. this._teleportationTarget.material = teleportationCircleMaterial;
  87032. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87033. torus.isPickable = false;
  87034. torus.parent = this._teleportationTarget;
  87035. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87036. var keys = [];
  87037. keys.push({
  87038. frame: 0,
  87039. value: 0
  87040. });
  87041. keys.push({
  87042. frame: 30,
  87043. value: 0.4
  87044. });
  87045. keys.push({
  87046. frame: 60,
  87047. value: 0
  87048. });
  87049. animationInnerCircle.setKeys(keys);
  87050. var easingFunction = new BABYLON.SineEase();
  87051. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87052. animationInnerCircle.setEasingFunction(easingFunction);
  87053. torus.animations = [];
  87054. torus.animations.push(animationInnerCircle);
  87055. this._scene.beginAnimation(torus, 0, 60, true);
  87056. this._hideTeleportationTarget();
  87057. };
  87058. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87059. this._teleportActive = true;
  87060. if (this._teleportationInitialized) {
  87061. this._teleportationTarget.isVisible = true;
  87062. if (this._isDefaultTeleportationTarget) {
  87063. this._teleportationTarget.getChildren()[0].isVisible = true;
  87064. }
  87065. }
  87066. };
  87067. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87068. this._teleportActive = false;
  87069. if (this._teleportationInitialized) {
  87070. this._teleportationTarget.isVisible = false;
  87071. if (this._isDefaultTeleportationTarget) {
  87072. this._teleportationTarget.getChildren()[0].isVisible = false;
  87073. }
  87074. }
  87075. };
  87076. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87077. var _this = this;
  87078. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87079. return;
  87080. }
  87081. if (right) {
  87082. this._rotationAngle++;
  87083. }
  87084. else {
  87085. this._rotationAngle--;
  87086. }
  87087. this.currentVRCamera.animations = [];
  87088. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87089. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87090. var animationRotationKeys = [];
  87091. animationRotationKeys.push({
  87092. frame: 0,
  87093. value: this.currentVRCamera.rotationQuaternion
  87094. });
  87095. animationRotationKeys.push({
  87096. frame: 6,
  87097. value: target
  87098. });
  87099. animationRotation.setKeys(animationRotationKeys);
  87100. animationRotation.setEasingFunction(this._circleEase);
  87101. this.currentVRCamera.animations.push(animationRotation);
  87102. this._postProcessMove.animations = [];
  87103. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87104. var vignetteWeightKeys = [];
  87105. vignetteWeightKeys.push({
  87106. frame: 0,
  87107. value: 0
  87108. });
  87109. vignetteWeightKeys.push({
  87110. frame: 3,
  87111. value: 4
  87112. });
  87113. vignetteWeightKeys.push({
  87114. frame: 6,
  87115. value: 0
  87116. });
  87117. animationPP.setKeys(vignetteWeightKeys);
  87118. animationPP.setEasingFunction(this._circleEase);
  87119. this._postProcessMove.animations.push(animationPP);
  87120. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87121. var vignetteStretchKeys = [];
  87122. vignetteStretchKeys.push({
  87123. frame: 0,
  87124. value: 0
  87125. });
  87126. vignetteStretchKeys.push({
  87127. frame: 3,
  87128. value: 10
  87129. });
  87130. vignetteStretchKeys.push({
  87131. frame: 6,
  87132. value: 0
  87133. });
  87134. animationPP2.setKeys(vignetteStretchKeys);
  87135. animationPP2.setEasingFunction(this._circleEase);
  87136. this._postProcessMove.animations.push(animationPP2);
  87137. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87138. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87139. this._postProcessMove.samples = 4;
  87140. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87141. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87142. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87143. });
  87144. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87145. };
  87146. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87147. if (hit.pickedPoint) {
  87148. if (gazer._teleportationRequestInitiated) {
  87149. this._displayTeleportationTarget();
  87150. this._haloCenter.copyFrom(hit.pickedPoint);
  87151. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87152. }
  87153. var pickNormal = hit.getNormal(true, false);
  87154. if (pickNormal) {
  87155. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87156. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87157. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87158. }
  87159. this._teleportationTarget.position.y += 0.1;
  87160. }
  87161. };
  87162. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87163. var _this = this;
  87164. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87165. return;
  87166. }
  87167. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87168. // offset of the headset from the anchor.
  87169. if (this.webVRCamera.leftCamera) {
  87170. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87171. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87172. location.subtractToRef(this._workingVector, this._workingVector);
  87173. }
  87174. else {
  87175. this._workingVector.copyFrom(location);
  87176. }
  87177. // Add height to account for user's height offset
  87178. if (this.isInVRMode) {
  87179. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87180. }
  87181. else {
  87182. this._workingVector.y += this._defaultHeight;
  87183. }
  87184. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87185. // Create animation from the camera's position to the new location
  87186. this.currentVRCamera.animations = [];
  87187. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87188. var animationCameraTeleportationKeys = [{
  87189. frame: 0,
  87190. value: this.currentVRCamera.position
  87191. },
  87192. {
  87193. frame: 11,
  87194. value: this._workingVector
  87195. }
  87196. ];
  87197. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87198. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87199. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87200. this._postProcessMove.animations = [];
  87201. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87202. var vignetteWeightKeys = [];
  87203. vignetteWeightKeys.push({
  87204. frame: 0,
  87205. value: 0
  87206. });
  87207. vignetteWeightKeys.push({
  87208. frame: 5,
  87209. value: 8
  87210. });
  87211. vignetteWeightKeys.push({
  87212. frame: 11,
  87213. value: 0
  87214. });
  87215. animationPP.setKeys(vignetteWeightKeys);
  87216. this._postProcessMove.animations.push(animationPP);
  87217. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87218. var vignetteStretchKeys = [];
  87219. vignetteStretchKeys.push({
  87220. frame: 0,
  87221. value: 0
  87222. });
  87223. vignetteStretchKeys.push({
  87224. frame: 5,
  87225. value: 10
  87226. });
  87227. vignetteStretchKeys.push({
  87228. frame: 11,
  87229. value: 0
  87230. });
  87231. animationPP2.setKeys(vignetteStretchKeys);
  87232. this._postProcessMove.animations.push(animationPP2);
  87233. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87234. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87235. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87236. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87237. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87238. });
  87239. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87240. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87241. });
  87242. this._hideTeleportationTarget();
  87243. };
  87244. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87245. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87246. return;
  87247. }
  87248. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87249. // Moving the gazeTracker on the mesh face targetted
  87250. if (hit && hit.pickedPoint) {
  87251. if (this._displayGaze) {
  87252. var multiplier = 1;
  87253. gazer._gazeTracker.isVisible = true;
  87254. if (gazer._isActionableMesh) {
  87255. multiplier = 3;
  87256. }
  87257. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87258. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87259. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87260. var pickNormal = hit.getNormal();
  87261. // To avoid z-fighting
  87262. var deltaFighting = 0.002;
  87263. if (pickNormal) {
  87264. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87265. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87266. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87267. }
  87268. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87269. if (gazer._gazeTracker.position.x < 0) {
  87270. gazer._gazeTracker.position.x += deltaFighting;
  87271. }
  87272. else {
  87273. gazer._gazeTracker.position.x -= deltaFighting;
  87274. }
  87275. if (gazer._gazeTracker.position.y < 0) {
  87276. gazer._gazeTracker.position.y += deltaFighting;
  87277. }
  87278. else {
  87279. gazer._gazeTracker.position.y -= deltaFighting;
  87280. }
  87281. if (gazer._gazeTracker.position.z < 0) {
  87282. gazer._gazeTracker.position.z += deltaFighting;
  87283. }
  87284. else {
  87285. gazer._gazeTracker.position.z -= deltaFighting;
  87286. }
  87287. }
  87288. // Changing the size of the laser pointer based on the distance from the targetted point
  87289. gazer._updatePointerDistance(hit.distance);
  87290. }
  87291. else {
  87292. gazer._gazeTracker.isVisible = false;
  87293. }
  87294. if (hit && hit.pickedMesh) {
  87295. gazer._currentHit = hit;
  87296. if (gazer._pointerDownOnMeshAsked) {
  87297. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87298. }
  87299. // The object selected is the floor, we're in a teleportation scenario
  87300. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87301. // Moving the teleportation area to this targetted point
  87302. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87303. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87304. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87305. }
  87306. gazer._currentMeshSelected = null;
  87307. if (gazer._teleportationRequestInitiated) {
  87308. this._moveTeleportationSelectorTo(hit, gazer);
  87309. }
  87310. return;
  87311. }
  87312. // If not, we're in a selection scenario
  87313. //this._teleportationAllowed = false;
  87314. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  87315. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  87316. this.onNewMeshPicked.notifyObservers(hit);
  87317. gazer._currentMeshSelected = hit.pickedMesh;
  87318. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  87319. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  87320. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  87321. gazer._isActionableMesh = true;
  87322. }
  87323. else {
  87324. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87325. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87326. gazer._isActionableMesh = false;
  87327. }
  87328. try {
  87329. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  87330. }
  87331. catch (err) {
  87332. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  87333. }
  87334. }
  87335. else {
  87336. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87337. gazer._currentMeshSelected = null;
  87338. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87339. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87340. }
  87341. }
  87342. }
  87343. else {
  87344. gazer._currentHit = null;
  87345. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87346. gazer._currentMeshSelected = null;
  87347. //this._teleportationAllowed = false;
  87348. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87349. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87350. }
  87351. };
  87352. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  87353. if (mesh) {
  87354. this.onSelectedMeshUnselected.notifyObservers(mesh);
  87355. }
  87356. };
  87357. /**
  87358. * Sets the color of the laser ray from the vr controllers.
  87359. * @param color new color for the ray.
  87360. */
  87361. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  87362. if (this.leftController) {
  87363. this.leftController._setLaserPointerColor(color);
  87364. }
  87365. if (this.rightController) {
  87366. this.rightController._setLaserPointerColor(color);
  87367. }
  87368. };
  87369. /**
  87370. * Sets the color of the ray from the vr headsets gaze.
  87371. * @param color new color for the ray.
  87372. */
  87373. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  87374. if (!this._cameraGazer._gazeTracker.material) {
  87375. return;
  87376. }
  87377. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  87378. if (this.leftController) {
  87379. this.leftController._gazeTracker.material.emissiveColor = color;
  87380. }
  87381. if (this.rightController) {
  87382. this.rightController._gazeTracker.material.emissiveColor = color;
  87383. }
  87384. };
  87385. /**
  87386. * Exits VR and disposes of the vr experience helper
  87387. */
  87388. VRExperienceHelper.prototype.dispose = function () {
  87389. if (this.isInVRMode) {
  87390. this.exitVR();
  87391. }
  87392. if (this._postProcessMove) {
  87393. this._postProcessMove.dispose();
  87394. }
  87395. if (this._webVRCamera) {
  87396. this._webVRCamera.dispose();
  87397. }
  87398. if (this._vrDeviceOrientationCamera) {
  87399. this._vrDeviceOrientationCamera.dispose();
  87400. }
  87401. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  87402. document.body.removeChild(this._btnVR);
  87403. }
  87404. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  87405. this._deviceOrientationCamera.dispose();
  87406. }
  87407. if (this._cameraGazer) {
  87408. this._cameraGazer.dispose();
  87409. }
  87410. if (this.leftController) {
  87411. this.leftController.dispose();
  87412. }
  87413. if (this.rightController) {
  87414. this.rightController.dispose();
  87415. }
  87416. if (this._teleportationTarget) {
  87417. this._teleportationTarget.dispose();
  87418. }
  87419. this._floorMeshesCollection = [];
  87420. document.removeEventListener("keydown", this._onKeyDown);
  87421. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87422. window.removeEventListener("resize", this._onResize);
  87423. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  87424. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  87425. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  87426. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  87427. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  87428. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  87429. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  87430. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87431. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  87432. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  87433. this._scene.unregisterBeforeRender(this.beforeRender);
  87434. };
  87435. /**
  87436. * Gets the name of the VRExperienceHelper class
  87437. * @returns "VRExperienceHelper"
  87438. */
  87439. VRExperienceHelper.prototype.getClassName = function () {
  87440. return "VRExperienceHelper";
  87441. };
  87442. return VRExperienceHelper;
  87443. }());
  87444. BABYLON.VRExperienceHelper = VRExperienceHelper;
  87445. })(BABYLON || (BABYLON = {}));
  87446. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  87447. // Mainly based on these 2 articles :
  87448. // 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
  87449. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  87450. var BABYLON;
  87451. (function (BABYLON) {
  87452. var JoystickAxis;
  87453. (function (JoystickAxis) {
  87454. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  87455. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  87456. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  87457. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  87458. var VirtualJoystick = /** @class */ (function () {
  87459. function VirtualJoystick(leftJoystick) {
  87460. var _this = this;
  87461. if (leftJoystick) {
  87462. this._leftJoystick = true;
  87463. }
  87464. else {
  87465. this._leftJoystick = false;
  87466. }
  87467. VirtualJoystick._globalJoystickIndex++;
  87468. // By default left & right arrow keys are moving the X
  87469. // and up & down keys are moving the Y
  87470. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87471. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87472. this.reverseLeftRight = false;
  87473. this.reverseUpDown = false;
  87474. // collections of pointers
  87475. this._touches = new BABYLON.StringDictionary();
  87476. this.deltaPosition = BABYLON.Vector3.Zero();
  87477. this._joystickSensibility = 25;
  87478. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87479. this._onResize = function (evt) {
  87480. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87481. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87482. if (VirtualJoystick.vjCanvas) {
  87483. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  87484. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  87485. }
  87486. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  87487. };
  87488. // injecting a canvas element on top of the canvas 3D game
  87489. if (!VirtualJoystick.vjCanvas) {
  87490. window.addEventListener("resize", this._onResize, false);
  87491. VirtualJoystick.vjCanvas = document.createElement("canvas");
  87492. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87493. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87494. VirtualJoystick.vjCanvas.width = window.innerWidth;
  87495. VirtualJoystick.vjCanvas.height = window.innerHeight;
  87496. VirtualJoystick.vjCanvas.style.width = "100%";
  87497. VirtualJoystick.vjCanvas.style.height = "100%";
  87498. VirtualJoystick.vjCanvas.style.position = "absolute";
  87499. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  87500. VirtualJoystick.vjCanvas.style.top = "0px";
  87501. VirtualJoystick.vjCanvas.style.left = "0px";
  87502. VirtualJoystick.vjCanvas.style.zIndex = "5";
  87503. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  87504. // Support for jQuery PEP polyfill
  87505. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  87506. var context = VirtualJoystick.vjCanvas.getContext('2d');
  87507. if (!context) {
  87508. throw new Error("Unable to create canvas for virtual joystick");
  87509. }
  87510. VirtualJoystick.vjCanvasContext = context;
  87511. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  87512. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87513. document.body.appendChild(VirtualJoystick.vjCanvas);
  87514. }
  87515. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  87516. this.pressed = false;
  87517. // default joystick color
  87518. this._joystickColor = "cyan";
  87519. this._joystickPointerID = -1;
  87520. // current joystick position
  87521. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  87522. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  87523. // origin joystick position
  87524. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  87525. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  87526. this._onPointerDownHandlerRef = function (evt) {
  87527. _this._onPointerDown(evt);
  87528. };
  87529. this._onPointerMoveHandlerRef = function (evt) {
  87530. _this._onPointerMove(evt);
  87531. };
  87532. this._onPointerUpHandlerRef = function (evt) {
  87533. _this._onPointerUp(evt);
  87534. };
  87535. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  87536. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  87537. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  87538. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  87539. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  87540. evt.preventDefault(); // Disables system menu
  87541. }, false);
  87542. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87543. }
  87544. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  87545. this._joystickSensibility = newJoystickSensibility;
  87546. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87547. };
  87548. VirtualJoystick.prototype._onPointerDown = function (e) {
  87549. var positionOnScreenCondition;
  87550. e.preventDefault();
  87551. if (this._leftJoystick === true) {
  87552. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  87553. }
  87554. else {
  87555. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  87556. }
  87557. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  87558. // First contact will be dedicated to the virtual joystick
  87559. this._joystickPointerID = e.pointerId;
  87560. this._joystickPointerStartPos.x = e.clientX;
  87561. this._joystickPointerStartPos.y = e.clientY;
  87562. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  87563. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  87564. this._deltaJoystickVector.x = 0;
  87565. this._deltaJoystickVector.y = 0;
  87566. this.pressed = true;
  87567. this._touches.add(e.pointerId.toString(), e);
  87568. }
  87569. else {
  87570. // You can only trigger the action buttons with a joystick declared
  87571. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  87572. this._action();
  87573. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  87574. }
  87575. }
  87576. };
  87577. VirtualJoystick.prototype._onPointerMove = function (e) {
  87578. // If the current pointer is the one associated to the joystick (first touch contact)
  87579. if (this._joystickPointerID == e.pointerId) {
  87580. this._joystickPointerPos.x = e.clientX;
  87581. this._joystickPointerPos.y = e.clientY;
  87582. this._deltaJoystickVector = this._joystickPointerPos.clone();
  87583. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  87584. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  87585. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  87586. switch (this._axisTargetedByLeftAndRight) {
  87587. case JoystickAxis.X:
  87588. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  87589. break;
  87590. case JoystickAxis.Y:
  87591. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  87592. break;
  87593. case JoystickAxis.Z:
  87594. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87595. break;
  87596. }
  87597. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87598. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87599. switch (this._axisTargetedByUpAndDown) {
  87600. case JoystickAxis.X:
  87601. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87602. break;
  87603. case JoystickAxis.Y:
  87604. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87605. break;
  87606. case JoystickAxis.Z:
  87607. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87608. break;
  87609. }
  87610. }
  87611. else {
  87612. var data = this._touches.get(e.pointerId.toString());
  87613. if (data) {
  87614. data.x = e.clientX;
  87615. data.y = e.clientY;
  87616. }
  87617. }
  87618. };
  87619. VirtualJoystick.prototype._onPointerUp = function (e) {
  87620. if (this._joystickPointerID == e.pointerId) {
  87621. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87622. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87623. this._joystickPointerID = -1;
  87624. this.pressed = false;
  87625. }
  87626. else {
  87627. var touch = this._touches.get(e.pointerId.toString());
  87628. if (touch) {
  87629. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87630. }
  87631. }
  87632. this._deltaJoystickVector.x = 0;
  87633. this._deltaJoystickVector.y = 0;
  87634. this._touches.remove(e.pointerId.toString());
  87635. };
  87636. /**
  87637. * Change the color of the virtual joystick
  87638. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87639. */
  87640. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87641. this._joystickColor = newColor;
  87642. };
  87643. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87644. this._action = action;
  87645. };
  87646. // Define which axis you'd like to control for left & right
  87647. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87648. switch (axis) {
  87649. case JoystickAxis.X:
  87650. case JoystickAxis.Y:
  87651. case JoystickAxis.Z:
  87652. this._axisTargetedByLeftAndRight = axis;
  87653. break;
  87654. default:
  87655. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87656. break;
  87657. }
  87658. };
  87659. // Define which axis you'd like to control for up & down
  87660. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87661. switch (axis) {
  87662. case JoystickAxis.X:
  87663. case JoystickAxis.Y:
  87664. case JoystickAxis.Z:
  87665. this._axisTargetedByUpAndDown = axis;
  87666. break;
  87667. default:
  87668. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87669. break;
  87670. }
  87671. };
  87672. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87673. var _this = this;
  87674. if (this.pressed) {
  87675. this._touches.forEach(function (key, touch) {
  87676. if (touch.pointerId === _this._joystickPointerID) {
  87677. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87678. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87679. VirtualJoystick.vjCanvasContext.beginPath();
  87680. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87681. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87682. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87683. VirtualJoystick.vjCanvasContext.stroke();
  87684. VirtualJoystick.vjCanvasContext.closePath();
  87685. VirtualJoystick.vjCanvasContext.beginPath();
  87686. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87687. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87688. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87689. VirtualJoystick.vjCanvasContext.stroke();
  87690. VirtualJoystick.vjCanvasContext.closePath();
  87691. VirtualJoystick.vjCanvasContext.beginPath();
  87692. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87693. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87694. VirtualJoystick.vjCanvasContext.stroke();
  87695. VirtualJoystick.vjCanvasContext.closePath();
  87696. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87697. }
  87698. else {
  87699. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87700. VirtualJoystick.vjCanvasContext.beginPath();
  87701. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87702. VirtualJoystick.vjCanvasContext.beginPath();
  87703. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87704. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87705. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87706. VirtualJoystick.vjCanvasContext.stroke();
  87707. VirtualJoystick.vjCanvasContext.closePath();
  87708. touch.prevX = touch.x;
  87709. touch.prevY = touch.y;
  87710. }
  87711. ;
  87712. });
  87713. }
  87714. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87715. };
  87716. VirtualJoystick.prototype.releaseCanvas = function () {
  87717. if (VirtualJoystick.vjCanvas) {
  87718. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87719. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87720. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87721. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87722. window.removeEventListener("resize", this._onResize);
  87723. document.body.removeChild(VirtualJoystick.vjCanvas);
  87724. VirtualJoystick.vjCanvas = null;
  87725. }
  87726. };
  87727. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87728. VirtualJoystick._globalJoystickIndex = 0;
  87729. return VirtualJoystick;
  87730. }());
  87731. BABYLON.VirtualJoystick = VirtualJoystick;
  87732. })(BABYLON || (BABYLON = {}));
  87733. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87734. var BABYLON;
  87735. (function (BABYLON) {
  87736. // We're mainly based on the logic defined into the FreeCamera code
  87737. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87738. __extends(VirtualJoysticksCamera, _super);
  87739. function VirtualJoysticksCamera(name, position, scene) {
  87740. var _this = _super.call(this, name, position, scene) || this;
  87741. _this.inputs.addVirtualJoystick();
  87742. return _this;
  87743. }
  87744. VirtualJoysticksCamera.prototype.getClassName = function () {
  87745. return "VirtualJoysticksCamera";
  87746. };
  87747. return VirtualJoysticksCamera;
  87748. }(BABYLON.FreeCamera));
  87749. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87750. })(BABYLON || (BABYLON = {}));
  87751. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87752. var BABYLON;
  87753. (function (BABYLON) {
  87754. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87755. function FreeCameraVirtualJoystickInput() {
  87756. }
  87757. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87758. return this._leftjoystick;
  87759. };
  87760. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87761. return this._rightjoystick;
  87762. };
  87763. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87764. if (this._leftjoystick) {
  87765. var camera = this.camera;
  87766. var speed = camera._computeLocalCameraSpeed() * 50;
  87767. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87768. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87769. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87770. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87771. if (!this._leftjoystick.pressed) {
  87772. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87773. }
  87774. if (!this._rightjoystick.pressed) {
  87775. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87776. }
  87777. }
  87778. };
  87779. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87780. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87781. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87782. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87783. this._leftjoystick.setJoystickSensibility(0.15);
  87784. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87785. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87786. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87787. this._rightjoystick.reverseUpDown = true;
  87788. this._rightjoystick.setJoystickSensibility(0.05);
  87789. this._rightjoystick.setJoystickColor("yellow");
  87790. };
  87791. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87792. this._leftjoystick.releaseCanvas();
  87793. this._rightjoystick.releaseCanvas();
  87794. };
  87795. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87796. return "FreeCameraVirtualJoystickInput";
  87797. };
  87798. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87799. return "virtualJoystick";
  87800. };
  87801. return FreeCameraVirtualJoystickInput;
  87802. }());
  87803. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87804. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87805. })(BABYLON || (BABYLON = {}));
  87806. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87807. var BABYLON;
  87808. (function (BABYLON) {
  87809. var SimplificationSettings = /** @class */ (function () {
  87810. function SimplificationSettings(quality, distance, optimizeMesh) {
  87811. this.quality = quality;
  87812. this.distance = distance;
  87813. this.optimizeMesh = optimizeMesh;
  87814. }
  87815. return SimplificationSettings;
  87816. }());
  87817. BABYLON.SimplificationSettings = SimplificationSettings;
  87818. var SimplificationQueue = /** @class */ (function () {
  87819. function SimplificationQueue() {
  87820. this.running = false;
  87821. this._simplificationArray = [];
  87822. }
  87823. SimplificationQueue.prototype.addTask = function (task) {
  87824. this._simplificationArray.push(task);
  87825. };
  87826. SimplificationQueue.prototype.executeNext = function () {
  87827. var task = this._simplificationArray.pop();
  87828. if (task) {
  87829. this.running = true;
  87830. this.runSimplification(task);
  87831. }
  87832. else {
  87833. this.running = false;
  87834. }
  87835. };
  87836. SimplificationQueue.prototype.runSimplification = function (task) {
  87837. var _this = this;
  87838. if (task.parallelProcessing) {
  87839. //parallel simplifier
  87840. task.settings.forEach(function (setting) {
  87841. var simplifier = _this.getSimplifier(task);
  87842. simplifier.simplify(setting, function (newMesh) {
  87843. task.mesh.addLODLevel(setting.distance, newMesh);
  87844. newMesh.isVisible = true;
  87845. //check if it is the last
  87846. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87847. //all done, run the success callback.
  87848. task.successCallback();
  87849. }
  87850. _this.executeNext();
  87851. });
  87852. });
  87853. }
  87854. else {
  87855. //single simplifier.
  87856. var simplifier = this.getSimplifier(task);
  87857. var runDecimation = function (setting, callback) {
  87858. simplifier.simplify(setting, function (newMesh) {
  87859. task.mesh.addLODLevel(setting.distance, newMesh);
  87860. newMesh.isVisible = true;
  87861. //run the next quality level
  87862. callback();
  87863. });
  87864. };
  87865. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87866. runDecimation(task.settings[loop.index], function () {
  87867. loop.executeNext();
  87868. });
  87869. }, function () {
  87870. //execution ended, run the success callback.
  87871. if (task.successCallback) {
  87872. task.successCallback();
  87873. }
  87874. _this.executeNext();
  87875. });
  87876. }
  87877. };
  87878. SimplificationQueue.prototype.getSimplifier = function (task) {
  87879. switch (task.simplificationType) {
  87880. case SimplificationType.QUADRATIC:
  87881. default:
  87882. return new QuadraticErrorSimplification(task.mesh);
  87883. }
  87884. };
  87885. return SimplificationQueue;
  87886. }());
  87887. BABYLON.SimplificationQueue = SimplificationQueue;
  87888. /**
  87889. * The implemented types of simplification.
  87890. * At the moment only Quadratic Error Decimation is implemented.
  87891. */
  87892. var SimplificationType;
  87893. (function (SimplificationType) {
  87894. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87895. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  87896. var DecimationTriangle = /** @class */ (function () {
  87897. function DecimationTriangle(vertices) {
  87898. this.vertices = vertices;
  87899. this.error = new Array(4);
  87900. this.deleted = false;
  87901. this.isDirty = false;
  87902. this.deletePending = false;
  87903. this.borderFactor = 0;
  87904. }
  87905. return DecimationTriangle;
  87906. }());
  87907. BABYLON.DecimationTriangle = DecimationTriangle;
  87908. var DecimationVertex = /** @class */ (function () {
  87909. function DecimationVertex(position, id) {
  87910. this.position = position;
  87911. this.id = id;
  87912. this.isBorder = true;
  87913. this.q = new QuadraticMatrix();
  87914. this.triangleCount = 0;
  87915. this.triangleStart = 0;
  87916. this.originalOffsets = [];
  87917. }
  87918. DecimationVertex.prototype.updatePosition = function (newPosition) {
  87919. this.position.copyFrom(newPosition);
  87920. };
  87921. return DecimationVertex;
  87922. }());
  87923. BABYLON.DecimationVertex = DecimationVertex;
  87924. var QuadraticMatrix = /** @class */ (function () {
  87925. function QuadraticMatrix(data) {
  87926. this.data = new Array(10);
  87927. for (var i = 0; i < 10; ++i) {
  87928. if (data && data[i]) {
  87929. this.data[i] = data[i];
  87930. }
  87931. else {
  87932. this.data[i] = 0;
  87933. }
  87934. }
  87935. }
  87936. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  87937. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  87938. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  87939. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  87940. return det;
  87941. };
  87942. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  87943. for (var i = 0; i < 10; ++i) {
  87944. this.data[i] += matrix.data[i];
  87945. }
  87946. };
  87947. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  87948. for (var i = 0; i < 10; ++i) {
  87949. this.data[i] += data[i];
  87950. }
  87951. };
  87952. QuadraticMatrix.prototype.add = function (matrix) {
  87953. var m = new QuadraticMatrix();
  87954. for (var i = 0; i < 10; ++i) {
  87955. m.data[i] = this.data[i] + matrix.data[i];
  87956. }
  87957. return m;
  87958. };
  87959. QuadraticMatrix.FromData = function (a, b, c, d) {
  87960. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  87961. };
  87962. //returning an array to avoid garbage collection
  87963. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  87964. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  87965. };
  87966. return QuadraticMatrix;
  87967. }());
  87968. BABYLON.QuadraticMatrix = QuadraticMatrix;
  87969. var Reference = /** @class */ (function () {
  87970. function Reference(vertexId, triangleId) {
  87971. this.vertexId = vertexId;
  87972. this.triangleId = triangleId;
  87973. }
  87974. return Reference;
  87975. }());
  87976. BABYLON.Reference = Reference;
  87977. /**
  87978. * An implementation of the Quadratic Error simplification algorithm.
  87979. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  87980. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  87981. * @author RaananW
  87982. */
  87983. var QuadraticErrorSimplification = /** @class */ (function () {
  87984. function QuadraticErrorSimplification(_mesh) {
  87985. this._mesh = _mesh;
  87986. this.syncIterations = 5000;
  87987. this.aggressiveness = 7;
  87988. this.decimationIterations = 100;
  87989. this.boundingBoxEpsilon = BABYLON.Epsilon;
  87990. }
  87991. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  87992. var _this = this;
  87993. this.initDecimatedMesh();
  87994. //iterating through the submeshes array, one after the other.
  87995. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  87996. _this.initWithMesh(loop.index, function () {
  87997. _this.runDecimation(settings, loop.index, function () {
  87998. loop.executeNext();
  87999. });
  88000. }, settings.optimizeMesh);
  88001. }, function () {
  88002. setTimeout(function () {
  88003. successCallback(_this._reconstructedMesh);
  88004. }, 0);
  88005. });
  88006. };
  88007. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88008. var _this = this;
  88009. var targetCount = ~~(this.triangles.length * settings.quality);
  88010. var deletedTriangles = 0;
  88011. var triangleCount = this.triangles.length;
  88012. var iterationFunction = function (iteration, callback) {
  88013. setTimeout(function () {
  88014. if (iteration % 5 === 0) {
  88015. _this.updateMesh(iteration === 0);
  88016. }
  88017. for (var i = 0; i < _this.triangles.length; ++i) {
  88018. _this.triangles[i].isDirty = false;
  88019. }
  88020. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88021. var trianglesIterator = function (i) {
  88022. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88023. var t = _this.triangles[tIdx];
  88024. if (!t)
  88025. return;
  88026. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88027. return;
  88028. }
  88029. for (var j = 0; j < 3; ++j) {
  88030. if (t.error[j] < threshold) {
  88031. var deleted0 = [];
  88032. var deleted1 = [];
  88033. var v0 = t.vertices[j];
  88034. var v1 = t.vertices[(j + 1) % 3];
  88035. if (v0.isBorder || v1.isBorder)
  88036. continue;
  88037. var p = BABYLON.Vector3.Zero();
  88038. var n = BABYLON.Vector3.Zero();
  88039. var uv = BABYLON.Vector2.Zero();
  88040. var color = new BABYLON.Color4(0, 0, 0, 1);
  88041. _this.calculateError(v0, v1, p, n, uv, color);
  88042. var delTr = new Array();
  88043. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88044. continue;
  88045. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88046. continue;
  88047. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88048. continue;
  88049. var uniqueArray = new Array();
  88050. delTr.forEach(function (deletedT) {
  88051. if (uniqueArray.indexOf(deletedT) === -1) {
  88052. deletedT.deletePending = true;
  88053. uniqueArray.push(deletedT);
  88054. }
  88055. });
  88056. if (uniqueArray.length % 2 !== 0) {
  88057. continue;
  88058. }
  88059. v0.q = v1.q.add(v0.q);
  88060. v0.updatePosition(p);
  88061. var tStart = _this.references.length;
  88062. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88063. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88064. var tCount = _this.references.length - tStart;
  88065. if (tCount <= v0.triangleCount) {
  88066. if (tCount) {
  88067. for (var c = 0; c < tCount; c++) {
  88068. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88069. }
  88070. }
  88071. }
  88072. else {
  88073. v0.triangleStart = tStart;
  88074. }
  88075. v0.triangleCount = tCount;
  88076. break;
  88077. }
  88078. }
  88079. };
  88080. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88081. }, 0);
  88082. };
  88083. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88084. if (triangleCount - deletedTriangles <= targetCount)
  88085. loop.breakLoop();
  88086. else {
  88087. iterationFunction(loop.index, function () {
  88088. loop.executeNext();
  88089. });
  88090. }
  88091. }, function () {
  88092. setTimeout(function () {
  88093. //reconstruct this part of the mesh
  88094. _this.reconstructMesh(submeshIndex);
  88095. successCallback();
  88096. }, 0);
  88097. });
  88098. };
  88099. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88100. var _this = this;
  88101. this.vertices = [];
  88102. this.triangles = [];
  88103. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88104. var indices = this._mesh.getIndices();
  88105. var submesh = this._mesh.subMeshes[submeshIndex];
  88106. var findInVertices = function (positionToSearch) {
  88107. if (optimizeMesh) {
  88108. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88109. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88110. return _this.vertices[ii];
  88111. }
  88112. }
  88113. }
  88114. return null;
  88115. };
  88116. var vertexReferences = [];
  88117. var vertexInit = function (i) {
  88118. if (!positionData) {
  88119. return;
  88120. }
  88121. var offset = i + submesh.verticesStart;
  88122. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88123. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88124. vertex.originalOffsets.push(offset);
  88125. if (vertex.id === _this.vertices.length) {
  88126. _this.vertices.push(vertex);
  88127. }
  88128. vertexReferences.push(vertex.id);
  88129. };
  88130. //var totalVertices = mesh.getTotalVertices();
  88131. var totalVertices = submesh.verticesCount;
  88132. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88133. var indicesInit = function (i) {
  88134. if (!indices) {
  88135. return;
  88136. }
  88137. var offset = (submesh.indexStart / 3) + i;
  88138. var pos = (offset * 3);
  88139. var i0 = indices[pos + 0];
  88140. var i1 = indices[pos + 1];
  88141. var i2 = indices[pos + 2];
  88142. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88143. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88144. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88145. var triangle = new DecimationTriangle([v0, v1, v2]);
  88146. triangle.originalOffset = pos;
  88147. _this.triangles.push(triangle);
  88148. };
  88149. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88150. _this.init(callback);
  88151. });
  88152. });
  88153. };
  88154. QuadraticErrorSimplification.prototype.init = function (callback) {
  88155. var _this = this;
  88156. var triangleInit1 = function (i) {
  88157. var t = _this.triangles[i];
  88158. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88159. for (var j = 0; j < 3; j++) {
  88160. 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))));
  88161. }
  88162. };
  88163. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88164. var triangleInit2 = function (i) {
  88165. var t = _this.triangles[i];
  88166. for (var j = 0; j < 3; ++j) {
  88167. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88168. }
  88169. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88170. };
  88171. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88172. callback();
  88173. });
  88174. });
  88175. };
  88176. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  88177. var newTriangles = [];
  88178. var i;
  88179. for (i = 0; i < this.vertices.length; ++i) {
  88180. this.vertices[i].triangleCount = 0;
  88181. }
  88182. var t;
  88183. var j;
  88184. for (i = 0; i < this.triangles.length; ++i) {
  88185. if (!this.triangles[i].deleted) {
  88186. t = this.triangles[i];
  88187. for (j = 0; j < 3; ++j) {
  88188. t.vertices[j].triangleCount = 1;
  88189. }
  88190. newTriangles.push(t);
  88191. }
  88192. }
  88193. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88194. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88195. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88196. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88197. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88198. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88199. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88200. var vertexCount = 0;
  88201. for (i = 0; i < this.vertices.length; ++i) {
  88202. var vertex = this.vertices[i];
  88203. vertex.id = vertexCount;
  88204. if (vertex.triangleCount) {
  88205. vertex.originalOffsets.forEach(function (originalOffset) {
  88206. if (!normalData) {
  88207. return;
  88208. }
  88209. newPositionData.push(vertex.position.x);
  88210. newPositionData.push(vertex.position.y);
  88211. newPositionData.push(vertex.position.z);
  88212. newNormalData.push(normalData[originalOffset * 3]);
  88213. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88214. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88215. if (uvs && uvs.length) {
  88216. newUVsData.push(uvs[(originalOffset * 2)]);
  88217. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88218. }
  88219. else if (colorsData && colorsData.length) {
  88220. newColorsData.push(colorsData[(originalOffset * 4)]);
  88221. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88222. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88223. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88224. }
  88225. ++vertexCount;
  88226. });
  88227. }
  88228. }
  88229. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88230. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88231. var submeshesArray = this._reconstructedMesh.subMeshes;
  88232. this._reconstructedMesh.subMeshes = [];
  88233. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88234. var originalIndices = this._mesh.getIndices();
  88235. for (i = 0; i < newTriangles.length; ++i) {
  88236. t = newTriangles[i]; //now get the new referencing point for each vertex
  88237. [0, 1, 2].forEach(function (idx) {
  88238. var id = originalIndices[t.originalOffset + idx];
  88239. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88240. if (offset < 0)
  88241. offset = 0;
  88242. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88243. });
  88244. }
  88245. //overwriting the old vertex buffers and indices.
  88246. this._reconstructedMesh.setIndices(newIndicesArray);
  88247. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88248. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88249. if (newUVsData.length > 0)
  88250. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88251. if (newColorsData.length > 0)
  88252. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88253. //create submesh
  88254. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88255. if (submeshIndex > 0) {
  88256. this._reconstructedMesh.subMeshes = [];
  88257. submeshesArray.forEach(function (submesh) {
  88258. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88259. });
  88260. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88261. }
  88262. };
  88263. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88264. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88265. this._reconstructedMesh.material = this._mesh.material;
  88266. this._reconstructedMesh.parent = this._mesh.parent;
  88267. this._reconstructedMesh.isVisible = false;
  88268. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88269. };
  88270. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88271. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88272. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88273. if (t.deleted)
  88274. continue;
  88275. var s = this.references[vertex1.triangleStart + i].vertexId;
  88276. var v1 = t.vertices[(s + 1) % 3];
  88277. var v2 = t.vertices[(s + 2) % 3];
  88278. if ((v1 === vertex2 || v2 === vertex2)) {
  88279. deletedArray[i] = true;
  88280. delTr.push(t);
  88281. continue;
  88282. }
  88283. var d1 = v1.position.subtract(point);
  88284. d1 = d1.normalize();
  88285. var d2 = v2.position.subtract(point);
  88286. d2 = d2.normalize();
  88287. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  88288. return true;
  88289. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  88290. deletedArray[i] = false;
  88291. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  88292. return true;
  88293. }
  88294. return false;
  88295. };
  88296. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  88297. var newDeleted = deletedTriangles;
  88298. for (var i = 0; i < vertex.triangleCount; ++i) {
  88299. var ref = this.references[vertex.triangleStart + i];
  88300. var t = this.triangles[ref.triangleId];
  88301. if (t.deleted)
  88302. continue;
  88303. if (deletedArray[i] && t.deletePending) {
  88304. t.deleted = true;
  88305. newDeleted++;
  88306. continue;
  88307. }
  88308. t.vertices[ref.vertexId] = origVertex;
  88309. t.isDirty = true;
  88310. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  88311. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  88312. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  88313. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88314. this.references.push(ref);
  88315. }
  88316. return newDeleted;
  88317. };
  88318. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  88319. for (var i = 0; i < this.vertices.length; ++i) {
  88320. var vCount = [];
  88321. var vId = [];
  88322. var v = this.vertices[i];
  88323. var j;
  88324. for (j = 0; j < v.triangleCount; ++j) {
  88325. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  88326. for (var ii = 0; ii < 3; ii++) {
  88327. var ofs = 0;
  88328. var vv = triangle.vertices[ii];
  88329. while (ofs < vCount.length) {
  88330. if (vId[ofs] === vv.id)
  88331. break;
  88332. ++ofs;
  88333. }
  88334. if (ofs === vCount.length) {
  88335. vCount.push(1);
  88336. vId.push(vv.id);
  88337. }
  88338. else {
  88339. vCount[ofs]++;
  88340. }
  88341. }
  88342. }
  88343. for (j = 0; j < vCount.length; ++j) {
  88344. if (vCount[j] === 1) {
  88345. this.vertices[vId[j]].isBorder = true;
  88346. }
  88347. else {
  88348. this.vertices[vId[j]].isBorder = false;
  88349. }
  88350. }
  88351. }
  88352. };
  88353. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  88354. if (identifyBorders === void 0) { identifyBorders = false; }
  88355. var i;
  88356. if (!identifyBorders) {
  88357. var newTrianglesVector = [];
  88358. for (i = 0; i < this.triangles.length; ++i) {
  88359. if (!this.triangles[i].deleted) {
  88360. newTrianglesVector.push(this.triangles[i]);
  88361. }
  88362. }
  88363. this.triangles = newTrianglesVector;
  88364. }
  88365. for (i = 0; i < this.vertices.length; ++i) {
  88366. this.vertices[i].triangleCount = 0;
  88367. this.vertices[i].triangleStart = 0;
  88368. }
  88369. var t;
  88370. var j;
  88371. var v;
  88372. for (i = 0; i < this.triangles.length; ++i) {
  88373. t = this.triangles[i];
  88374. for (j = 0; j < 3; ++j) {
  88375. v = t.vertices[j];
  88376. v.triangleCount++;
  88377. }
  88378. }
  88379. var tStart = 0;
  88380. for (i = 0; i < this.vertices.length; ++i) {
  88381. this.vertices[i].triangleStart = tStart;
  88382. tStart += this.vertices[i].triangleCount;
  88383. this.vertices[i].triangleCount = 0;
  88384. }
  88385. var newReferences = new Array(this.triangles.length * 3);
  88386. for (i = 0; i < this.triangles.length; ++i) {
  88387. t = this.triangles[i];
  88388. for (j = 0; j < 3; ++j) {
  88389. v = t.vertices[j];
  88390. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  88391. v.triangleCount++;
  88392. }
  88393. }
  88394. this.references = newReferences;
  88395. if (identifyBorders) {
  88396. this.identifyBorder();
  88397. }
  88398. };
  88399. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  88400. var x = point.x;
  88401. var y = point.y;
  88402. var z = point.z;
  88403. 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
  88404. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  88405. };
  88406. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  88407. var q = vertex1.q.add(vertex2.q);
  88408. var border = vertex1.isBorder && vertex2.isBorder;
  88409. var error = 0;
  88410. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  88411. if (qDet !== 0 && !border) {
  88412. if (!pointResult) {
  88413. pointResult = BABYLON.Vector3.Zero();
  88414. }
  88415. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  88416. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  88417. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  88418. error = this.vertexError(q, pointResult);
  88419. }
  88420. else {
  88421. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  88422. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  88423. var error1 = this.vertexError(q, vertex1.position);
  88424. var error2 = this.vertexError(q, vertex2.position);
  88425. var error3 = this.vertexError(q, p3);
  88426. error = Math.min(error1, error2, error3);
  88427. if (error === error1) {
  88428. if (pointResult) {
  88429. pointResult.copyFrom(vertex1.position);
  88430. }
  88431. }
  88432. else if (error === error2) {
  88433. if (pointResult) {
  88434. pointResult.copyFrom(vertex2.position);
  88435. }
  88436. }
  88437. else {
  88438. if (pointResult) {
  88439. pointResult.copyFrom(p3);
  88440. }
  88441. }
  88442. }
  88443. return error;
  88444. };
  88445. return QuadraticErrorSimplification;
  88446. }());
  88447. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  88448. })(BABYLON || (BABYLON = {}));
  88449. //# sourceMappingURL=babylon.meshSimplification.js.map
  88450. var BABYLON;
  88451. (function (BABYLON) {
  88452. var MeshLODLevel = /** @class */ (function () {
  88453. function MeshLODLevel(distance, mesh) {
  88454. this.distance = distance;
  88455. this.mesh = mesh;
  88456. }
  88457. return MeshLODLevel;
  88458. }());
  88459. BABYLON.MeshLODLevel = MeshLODLevel;
  88460. })(BABYLON || (BABYLON = {}));
  88461. //# sourceMappingURL=babylon.meshLODLevel.js.map
  88462. var BABYLON;
  88463. (function (BABYLON) {
  88464. /**
  88465. * Defines the root class used to create scene optimization to use with SceneOptimizer
  88466. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88467. */
  88468. var SceneOptimization = /** @class */ (function () {
  88469. /**
  88470. * Creates the SceneOptimization object
  88471. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88472. * @param desc defines the description associated with the optimization
  88473. */
  88474. function SceneOptimization(
  88475. /**
  88476. * Defines the priority of this optimization (0 by default which means first in the list)
  88477. */
  88478. priority) {
  88479. if (priority === void 0) { priority = 0; }
  88480. this.priority = priority;
  88481. }
  88482. /**
  88483. * Gets a string describing the action executed by the current optimization
  88484. * @returns description string
  88485. */
  88486. SceneOptimization.prototype.getDescription = function () {
  88487. return "";
  88488. };
  88489. /**
  88490. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88491. * @param scene defines the current scene where to apply this optimization
  88492. * @param optimizer defines the current optimizer
  88493. * @returns true if everything that can be done was applied
  88494. */
  88495. SceneOptimization.prototype.apply = function (scene, optimizer) {
  88496. return true;
  88497. };
  88498. ;
  88499. return SceneOptimization;
  88500. }());
  88501. BABYLON.SceneOptimization = SceneOptimization;
  88502. /**
  88503. * Defines an optimization used to reduce the size of render target textures
  88504. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88505. */
  88506. var TextureOptimization = /** @class */ (function (_super) {
  88507. __extends(TextureOptimization, _super);
  88508. /**
  88509. * Creates the TextureOptimization object
  88510. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88511. * @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
  88512. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88513. */
  88514. function TextureOptimization(
  88515. /**
  88516. * Defines the priority of this optimization (0 by default which means first in the list)
  88517. */
  88518. priority,
  88519. /**
  88520. * 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
  88521. */
  88522. maximumSize,
  88523. /**
  88524. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88525. */
  88526. step) {
  88527. if (priority === void 0) { priority = 0; }
  88528. if (maximumSize === void 0) { maximumSize = 1024; }
  88529. if (step === void 0) { step = 0.5; }
  88530. var _this = _super.call(this, priority) || this;
  88531. _this.priority = priority;
  88532. _this.maximumSize = maximumSize;
  88533. _this.step = step;
  88534. return _this;
  88535. }
  88536. /**
  88537. * Gets a string describing the action executed by the current optimization
  88538. * @returns description string
  88539. */
  88540. TextureOptimization.prototype.getDescription = function () {
  88541. return "Reducing render target texture size to " + this.maximumSize;
  88542. };
  88543. /**
  88544. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88545. * @param scene defines the current scene where to apply this optimization
  88546. * @param optimizer defines the current optimizer
  88547. * @returns true if everything that can be done was applied
  88548. */
  88549. TextureOptimization.prototype.apply = function (scene, optimizer) {
  88550. var allDone = true;
  88551. for (var index = 0; index < scene.textures.length; index++) {
  88552. var texture = scene.textures[index];
  88553. if (!texture.canRescale || texture.getContext) {
  88554. continue;
  88555. }
  88556. var currentSize = texture.getSize();
  88557. var maxDimension = Math.max(currentSize.width, currentSize.height);
  88558. if (maxDimension > this.maximumSize) {
  88559. texture.scale(this.step);
  88560. allDone = false;
  88561. }
  88562. }
  88563. return allDone;
  88564. };
  88565. return TextureOptimization;
  88566. }(SceneOptimization));
  88567. BABYLON.TextureOptimization = TextureOptimization;
  88568. /**
  88569. * Defines an optimization used to increase or decrease the rendering resolution
  88570. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88571. */
  88572. var HardwareScalingOptimization = /** @class */ (function (_super) {
  88573. __extends(HardwareScalingOptimization, _super);
  88574. /**
  88575. * Creates the HardwareScalingOptimization object
  88576. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88577. * @param maximumScale defines the maximum scale to use (2 by default)
  88578. * @param step defines the step to use between two passes (0.5 by default)
  88579. */
  88580. function HardwareScalingOptimization(
  88581. /**
  88582. * Defines the priority of this optimization (0 by default which means first in the list)
  88583. */
  88584. priority,
  88585. /**
  88586. * Defines the maximum scale to use (2 by default)
  88587. */
  88588. maximumScale,
  88589. /**
  88590. * Defines the step to use between two passes (0.5 by default)
  88591. */
  88592. step) {
  88593. if (priority === void 0) { priority = 0; }
  88594. if (maximumScale === void 0) { maximumScale = 2; }
  88595. if (step === void 0) { step = 0.25; }
  88596. var _this = _super.call(this, priority) || this;
  88597. _this.priority = priority;
  88598. _this.maximumScale = maximumScale;
  88599. _this.step = step;
  88600. _this._currentScale = -1;
  88601. _this._directionOffset = 1;
  88602. return _this;
  88603. }
  88604. /**
  88605. * Gets a string describing the action executed by the current optimization
  88606. * @return description string
  88607. */
  88608. HardwareScalingOptimization.prototype.getDescription = function () {
  88609. return "Setting hardware scaling level to " + this._currentScale;
  88610. };
  88611. /**
  88612. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88613. * @param scene defines the current scene where to apply this optimization
  88614. * @param optimizer defines the current optimizer
  88615. * @returns true if everything that can be done was applied
  88616. */
  88617. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88618. if (this._currentScale === -1) {
  88619. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88620. if (this._currentScale > this.maximumScale) {
  88621. this._directionOffset = -1;
  88622. }
  88623. }
  88624. this._currentScale += this._directionOffset * this.step;
  88625. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88626. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88627. };
  88628. ;
  88629. return HardwareScalingOptimization;
  88630. }(SceneOptimization));
  88631. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88632. /**
  88633. * Defines an optimization used to remove shadows
  88634. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88635. */
  88636. var ShadowsOptimization = /** @class */ (function (_super) {
  88637. __extends(ShadowsOptimization, _super);
  88638. function ShadowsOptimization() {
  88639. return _super !== null && _super.apply(this, arguments) || this;
  88640. }
  88641. /**
  88642. * Gets a string describing the action executed by the current optimization
  88643. * @return description string
  88644. */
  88645. ShadowsOptimization.prototype.getDescription = function () {
  88646. return "Turning shadows on/off";
  88647. };
  88648. /**
  88649. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88650. * @param scene defines the current scene where to apply this optimization
  88651. * @param optimizer defines the current optimizer
  88652. * @returns true if everything that can be done was applied
  88653. */
  88654. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88655. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88656. return true;
  88657. };
  88658. ;
  88659. return ShadowsOptimization;
  88660. }(SceneOptimization));
  88661. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88662. /**
  88663. * Defines an optimization used to turn post-processes off
  88664. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88665. */
  88666. var PostProcessesOptimization = /** @class */ (function (_super) {
  88667. __extends(PostProcessesOptimization, _super);
  88668. function PostProcessesOptimization() {
  88669. return _super !== null && _super.apply(this, arguments) || this;
  88670. }
  88671. /**
  88672. * Gets a string describing the action executed by the current optimization
  88673. * @return description string
  88674. */
  88675. PostProcessesOptimization.prototype.getDescription = function () {
  88676. return "Turning post-processes on/off";
  88677. };
  88678. /**
  88679. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88680. * @param scene defines the current scene where to apply this optimization
  88681. * @param optimizer defines the current optimizer
  88682. * @returns true if everything that can be done was applied
  88683. */
  88684. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88685. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88686. return true;
  88687. };
  88688. ;
  88689. return PostProcessesOptimization;
  88690. }(SceneOptimization));
  88691. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88692. /**
  88693. * Defines an optimization used to turn lens flares off
  88694. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88695. */
  88696. var LensFlaresOptimization = /** @class */ (function (_super) {
  88697. __extends(LensFlaresOptimization, _super);
  88698. function LensFlaresOptimization() {
  88699. return _super !== null && _super.apply(this, arguments) || this;
  88700. }
  88701. /**
  88702. * Gets a string describing the action executed by the current optimization
  88703. * @return description string
  88704. */
  88705. LensFlaresOptimization.prototype.getDescription = function () {
  88706. return "Turning lens flares on/off";
  88707. };
  88708. /**
  88709. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88710. * @param scene defines the current scene where to apply this optimization
  88711. * @param optimizer defines the current optimizer
  88712. * @returns true if everything that can be done was applied
  88713. */
  88714. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88715. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88716. return true;
  88717. };
  88718. ;
  88719. return LensFlaresOptimization;
  88720. }(SceneOptimization));
  88721. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88722. /**
  88723. * Defines an optimization based on user defined callback.
  88724. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88725. */
  88726. var CustomOptimization = /** @class */ (function (_super) {
  88727. __extends(CustomOptimization, _super);
  88728. function CustomOptimization() {
  88729. return _super !== null && _super.apply(this, arguments) || this;
  88730. }
  88731. /**
  88732. * Gets a string describing the action executed by the current optimization
  88733. * @returns description string
  88734. */
  88735. CustomOptimization.prototype.getDescription = function () {
  88736. if (this.onGetDescription) {
  88737. return this.onGetDescription();
  88738. }
  88739. return "Running user defined callback";
  88740. };
  88741. /**
  88742. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88743. * @param scene defines the current scene where to apply this optimization
  88744. * @param optimizer defines the current optimizer
  88745. * @returns true if everything that can be done was applied
  88746. */
  88747. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88748. if (this.onApply) {
  88749. return this.onApply(scene, optimizer);
  88750. }
  88751. return true;
  88752. };
  88753. ;
  88754. return CustomOptimization;
  88755. }(SceneOptimization));
  88756. BABYLON.CustomOptimization = CustomOptimization;
  88757. /**
  88758. * Defines an optimization used to turn particles off
  88759. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88760. */
  88761. var ParticlesOptimization = /** @class */ (function (_super) {
  88762. __extends(ParticlesOptimization, _super);
  88763. function ParticlesOptimization() {
  88764. return _super !== null && _super.apply(this, arguments) || this;
  88765. }
  88766. /**
  88767. * Gets a string describing the action executed by the current optimization
  88768. * @return description string
  88769. */
  88770. ParticlesOptimization.prototype.getDescription = function () {
  88771. return "Turning particles on/off";
  88772. };
  88773. /**
  88774. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88775. * @param scene defines the current scene where to apply this optimization
  88776. * @param optimizer defines the current optimizer
  88777. * @returns true if everything that can be done was applied
  88778. */
  88779. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88780. scene.particlesEnabled = optimizer.isInImprovementMode;
  88781. return true;
  88782. };
  88783. ;
  88784. return ParticlesOptimization;
  88785. }(SceneOptimization));
  88786. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88787. /**
  88788. * Defines an optimization used to turn render targets off
  88789. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88790. */
  88791. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88792. __extends(RenderTargetsOptimization, _super);
  88793. function RenderTargetsOptimization() {
  88794. return _super !== null && _super.apply(this, arguments) || this;
  88795. }
  88796. /**
  88797. * Gets a string describing the action executed by the current optimization
  88798. * @return description string
  88799. */
  88800. RenderTargetsOptimization.prototype.getDescription = function () {
  88801. return "Turning render targets off";
  88802. };
  88803. /**
  88804. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88805. * @param scene defines the current scene where to apply this optimization
  88806. * @param optimizer defines the current optimizer
  88807. * @returns true if everything that can be done was applied
  88808. */
  88809. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88810. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88811. return true;
  88812. };
  88813. ;
  88814. return RenderTargetsOptimization;
  88815. }(SceneOptimization));
  88816. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88817. /**
  88818. * Defines an optimization used to merge meshes with compatible materials
  88819. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88820. */
  88821. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88822. __extends(MergeMeshesOptimization, _super);
  88823. function MergeMeshesOptimization() {
  88824. var _this = _super !== null && _super.apply(this, arguments) || this;
  88825. _this._canBeMerged = function (abstractMesh) {
  88826. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88827. return false;
  88828. }
  88829. var mesh = abstractMesh;
  88830. if (!mesh.isVisible || !mesh.isEnabled()) {
  88831. return false;
  88832. }
  88833. if (mesh.instances.length > 0) {
  88834. return false;
  88835. }
  88836. if (mesh.skeleton || mesh.hasLODLevels) {
  88837. return false;
  88838. }
  88839. if (mesh.parent) {
  88840. return false;
  88841. }
  88842. return true;
  88843. };
  88844. return _this;
  88845. }
  88846. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88847. /**
  88848. * Gets or sets a boolean which defines if optimization octree has to be updated
  88849. */
  88850. get: function () {
  88851. return MergeMeshesOptimization._UpdateSelectionTree;
  88852. },
  88853. /**
  88854. * Gets or sets a boolean which defines if optimization octree has to be updated
  88855. */
  88856. set: function (value) {
  88857. MergeMeshesOptimization._UpdateSelectionTree = value;
  88858. },
  88859. enumerable: true,
  88860. configurable: true
  88861. });
  88862. /**
  88863. * Gets a string describing the action executed by the current optimization
  88864. * @return description string
  88865. */
  88866. MergeMeshesOptimization.prototype.getDescription = function () {
  88867. return "Merging similar meshes together";
  88868. };
  88869. /**
  88870. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88871. * @param scene defines the current scene where to apply this optimization
  88872. * @param optimizer defines the current optimizer
  88873. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88874. * @returns true if everything that can be done was applied
  88875. */
  88876. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88877. var globalPool = scene.meshes.slice(0);
  88878. var globalLength = globalPool.length;
  88879. for (var index = 0; index < globalLength; index++) {
  88880. var currentPool = new Array();
  88881. var current = globalPool[index];
  88882. // Checks
  88883. if (!this._canBeMerged(current)) {
  88884. continue;
  88885. }
  88886. currentPool.push(current);
  88887. // Find compatible meshes
  88888. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  88889. var otherMesh = globalPool[subIndex];
  88890. if (!this._canBeMerged(otherMesh)) {
  88891. continue;
  88892. }
  88893. if (otherMesh.material !== current.material) {
  88894. continue;
  88895. }
  88896. if (otherMesh.checkCollisions !== current.checkCollisions) {
  88897. continue;
  88898. }
  88899. currentPool.push(otherMesh);
  88900. globalLength--;
  88901. globalPool.splice(subIndex, 1);
  88902. subIndex--;
  88903. }
  88904. if (currentPool.length < 2) {
  88905. continue;
  88906. }
  88907. // Merge meshes
  88908. BABYLON.Mesh.MergeMeshes(currentPool);
  88909. }
  88910. if (updateSelectionTree != undefined) {
  88911. if (updateSelectionTree) {
  88912. scene.createOrUpdateSelectionOctree();
  88913. }
  88914. }
  88915. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  88916. scene.createOrUpdateSelectionOctree();
  88917. }
  88918. return true;
  88919. };
  88920. ;
  88921. MergeMeshesOptimization._UpdateSelectionTree = false;
  88922. return MergeMeshesOptimization;
  88923. }(SceneOptimization));
  88924. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  88925. /**
  88926. * Defines a list of options used by SceneOptimizer
  88927. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88928. */
  88929. var SceneOptimizerOptions = /** @class */ (function () {
  88930. /**
  88931. * Creates a new list of options used by SceneOptimizer
  88932. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  88933. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  88934. */
  88935. function SceneOptimizerOptions(
  88936. /**
  88937. * Defines the target frame rate to reach (60 by default)
  88938. */
  88939. targetFrameRate,
  88940. /**
  88941. * Defines the interval between two checkes (2000ms by default)
  88942. */
  88943. trackerDuration) {
  88944. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  88945. if (trackerDuration === void 0) { trackerDuration = 2000; }
  88946. this.targetFrameRate = targetFrameRate;
  88947. this.trackerDuration = trackerDuration;
  88948. /**
  88949. * Gets the list of optimizations to apply
  88950. */
  88951. this.optimizations = new Array();
  88952. }
  88953. /**
  88954. * Add a new optimization
  88955. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  88956. * @returns the current SceneOptimizerOptions
  88957. */
  88958. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  88959. this.optimizations.push(optimization);
  88960. return this;
  88961. };
  88962. /**
  88963. * Add a new custom optimization
  88964. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  88965. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  88966. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88967. * @returns the current SceneOptimizerOptions
  88968. */
  88969. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  88970. if (priority === void 0) { priority = 0; }
  88971. var optimization = new CustomOptimization(priority);
  88972. optimization.onApply = onApply;
  88973. optimization.onGetDescription = onGetDescription;
  88974. this.optimizations.push(optimization);
  88975. return this;
  88976. };
  88977. /**
  88978. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  88979. * @param targetFrameRate defines the target frame rate (60 by default)
  88980. * @returns a SceneOptimizerOptions object
  88981. */
  88982. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  88983. var result = new SceneOptimizerOptions(targetFrameRate);
  88984. var priority = 0;
  88985. result.addOptimization(new MergeMeshesOptimization(priority));
  88986. result.addOptimization(new ShadowsOptimization(priority));
  88987. result.addOptimization(new LensFlaresOptimization(priority));
  88988. // Next priority
  88989. priority++;
  88990. result.addOptimization(new PostProcessesOptimization(priority));
  88991. result.addOptimization(new ParticlesOptimization(priority));
  88992. // Next priority
  88993. priority++;
  88994. result.addOptimization(new TextureOptimization(priority, 1024));
  88995. return result;
  88996. };
  88997. /**
  88998. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  88999. * @param targetFrameRate defines the target frame rate (60 by default)
  89000. * @returns a SceneOptimizerOptions object
  89001. */
  89002. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89003. var result = new SceneOptimizerOptions(targetFrameRate);
  89004. var priority = 0;
  89005. result.addOptimization(new MergeMeshesOptimization(priority));
  89006. result.addOptimization(new ShadowsOptimization(priority));
  89007. result.addOptimization(new LensFlaresOptimization(priority));
  89008. // Next priority
  89009. priority++;
  89010. result.addOptimization(new PostProcessesOptimization(priority));
  89011. result.addOptimization(new ParticlesOptimization(priority));
  89012. // Next priority
  89013. priority++;
  89014. result.addOptimization(new TextureOptimization(priority, 512));
  89015. // Next priority
  89016. priority++;
  89017. result.addOptimization(new RenderTargetsOptimization(priority));
  89018. // Next priority
  89019. priority++;
  89020. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89021. return result;
  89022. };
  89023. /**
  89024. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89025. * @param targetFrameRate defines the target frame rate (60 by default)
  89026. * @returns a SceneOptimizerOptions object
  89027. */
  89028. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89029. var result = new SceneOptimizerOptions(targetFrameRate);
  89030. var priority = 0;
  89031. result.addOptimization(new MergeMeshesOptimization(priority));
  89032. result.addOptimization(new ShadowsOptimization(priority));
  89033. result.addOptimization(new LensFlaresOptimization(priority));
  89034. // Next priority
  89035. priority++;
  89036. result.addOptimization(new PostProcessesOptimization(priority));
  89037. result.addOptimization(new ParticlesOptimization(priority));
  89038. // Next priority
  89039. priority++;
  89040. result.addOptimization(new TextureOptimization(priority, 256));
  89041. // Next priority
  89042. priority++;
  89043. result.addOptimization(new RenderTargetsOptimization(priority));
  89044. // Next priority
  89045. priority++;
  89046. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89047. return result;
  89048. };
  89049. return SceneOptimizerOptions;
  89050. }());
  89051. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89052. /**
  89053. * Class used to run optimizations in order to reach a target frame rate
  89054. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89055. */
  89056. var SceneOptimizer = /** @class */ (function () {
  89057. /**
  89058. * Creates a new SceneOptimizer
  89059. * @param scene defines the scene to work on
  89060. * @param options defines the options to use with the SceneOptimizer
  89061. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89062. * @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)
  89063. */
  89064. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89065. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89066. if (improvementMode === void 0) { improvementMode = false; }
  89067. var _this = this;
  89068. this._isRunning = false;
  89069. this._currentPriorityLevel = 0;
  89070. this._targetFrameRate = 60;
  89071. this._trackerDuration = 2000;
  89072. this._currentFrameRate = 0;
  89073. this._improvementMode = false;
  89074. /**
  89075. * Defines an observable called when the optimizer reaches the target frame rate
  89076. */
  89077. this.onSuccessObservable = new BABYLON.Observable();
  89078. /**
  89079. * Defines an observable called when the optimizer enables an optimization
  89080. */
  89081. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89082. /**
  89083. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89084. */
  89085. this.onFailureObservable = new BABYLON.Observable();
  89086. if (!options) {
  89087. this._options = new SceneOptimizerOptions();
  89088. }
  89089. else {
  89090. this._options = options;
  89091. }
  89092. if (this._options.targetFrameRate) {
  89093. this._targetFrameRate = this._options.targetFrameRate;
  89094. }
  89095. if (this._options.trackerDuration) {
  89096. this._trackerDuration = this._options.trackerDuration;
  89097. }
  89098. if (autoGeneratePriorities) {
  89099. var priority = 0;
  89100. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89101. var optim = _a[_i];
  89102. optim.priority = priority++;
  89103. }
  89104. }
  89105. this._improvementMode = improvementMode;
  89106. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89107. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89108. _this._sceneDisposeObserver = null;
  89109. _this.dispose();
  89110. });
  89111. }
  89112. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89113. /**
  89114. * Gets a boolean indicating if the optimizer is in improvement mode
  89115. */
  89116. get: function () {
  89117. return this._improvementMode;
  89118. },
  89119. enumerable: true,
  89120. configurable: true
  89121. });
  89122. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89123. /**
  89124. * Gets the current priority level (0 at start)
  89125. */
  89126. get: function () {
  89127. return this._currentPriorityLevel;
  89128. },
  89129. enumerable: true,
  89130. configurable: true
  89131. });
  89132. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89133. /**
  89134. * Gets the current frame rate checked by the SceneOptimizer
  89135. */
  89136. get: function () {
  89137. return this._currentFrameRate;
  89138. },
  89139. enumerable: true,
  89140. configurable: true
  89141. });
  89142. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89143. /**
  89144. * Gets or sets the current target frame rate (60 by default)
  89145. */
  89146. get: function () {
  89147. return this._targetFrameRate;
  89148. },
  89149. /**
  89150. * Gets or sets the current target frame rate (60 by default)
  89151. */
  89152. set: function (value) {
  89153. this._targetFrameRate = value;
  89154. },
  89155. enumerable: true,
  89156. configurable: true
  89157. });
  89158. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89159. /**
  89160. * Gets or sets the current interval between two checks (every 2000ms by default)
  89161. */
  89162. get: function () {
  89163. return this._trackerDuration;
  89164. },
  89165. /**
  89166. * Gets or sets the current interval between two checks (every 2000ms by default)
  89167. */
  89168. set: function (value) {
  89169. this._trackerDuration = value;
  89170. },
  89171. enumerable: true,
  89172. configurable: true
  89173. });
  89174. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  89175. /**
  89176. * Gets the list of active optimizations
  89177. */
  89178. get: function () {
  89179. return this._options.optimizations;
  89180. },
  89181. enumerable: true,
  89182. configurable: true
  89183. });
  89184. /**
  89185. * Stops the current optimizer
  89186. */
  89187. SceneOptimizer.prototype.stop = function () {
  89188. this._isRunning = false;
  89189. };
  89190. /**
  89191. * Reset the optimizer to initial step (current priority level = 0)
  89192. */
  89193. SceneOptimizer.prototype.reset = function () {
  89194. this._currentPriorityLevel = 0;
  89195. };
  89196. /**
  89197. * Start the optimizer. By default it will try to reach a specific framerate
  89198. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89199. */
  89200. SceneOptimizer.prototype.start = function () {
  89201. var _this = this;
  89202. if (this._isRunning) {
  89203. return;
  89204. }
  89205. this._isRunning = true;
  89206. // Let's wait for the scene to be ready before running our check
  89207. this._scene.executeWhenReady(function () {
  89208. setTimeout(function () {
  89209. _this._checkCurrentState();
  89210. }, _this._trackerDuration);
  89211. });
  89212. };
  89213. SceneOptimizer.prototype._checkCurrentState = function () {
  89214. var _this = this;
  89215. if (!this._isRunning) {
  89216. return;
  89217. }
  89218. var scene = this._scene;
  89219. var options = this._options;
  89220. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89221. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89222. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89223. this._isRunning = false;
  89224. this.onSuccessObservable.notifyObservers(this);
  89225. return;
  89226. }
  89227. // Apply current level of optimizations
  89228. var allDone = true;
  89229. var noOptimizationApplied = true;
  89230. for (var index = 0; index < options.optimizations.length; index++) {
  89231. var optimization = options.optimizations[index];
  89232. if (optimization.priority === this._currentPriorityLevel) {
  89233. noOptimizationApplied = false;
  89234. allDone = allDone && optimization.apply(scene, this);
  89235. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89236. }
  89237. }
  89238. // If no optimization was applied, this is a failure :(
  89239. if (noOptimizationApplied) {
  89240. this._isRunning = false;
  89241. this.onFailureObservable.notifyObservers(this);
  89242. return;
  89243. }
  89244. // If all optimizations were done, move to next level
  89245. if (allDone) {
  89246. this._currentPriorityLevel++;
  89247. }
  89248. // Let's the system running for a specific amount of time before checking FPS
  89249. scene.executeWhenReady(function () {
  89250. setTimeout(function () {
  89251. _this._checkCurrentState();
  89252. }, _this._trackerDuration);
  89253. });
  89254. };
  89255. /**
  89256. * Release all resources
  89257. */
  89258. SceneOptimizer.prototype.dispose = function () {
  89259. this.stop();
  89260. this.onSuccessObservable.clear();
  89261. this.onFailureObservable.clear();
  89262. this.onNewOptimizationAppliedObservable.clear();
  89263. if (this._sceneDisposeObserver) {
  89264. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89265. }
  89266. };
  89267. /**
  89268. * Helper function to create a SceneOptimizer with one single line of code
  89269. * @param scene defines the scene to work on
  89270. * @param options defines the options to use with the SceneOptimizer
  89271. * @param onSuccess defines a callback to call on success
  89272. * @param onFailure defines a callback to call on failure
  89273. * @returns the new SceneOptimizer object
  89274. */
  89275. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89276. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89277. if (onSuccess) {
  89278. optimizer.onSuccessObservable.add(function () {
  89279. onSuccess();
  89280. });
  89281. }
  89282. if (onFailure) {
  89283. optimizer.onFailureObservable.add(function () {
  89284. onFailure();
  89285. });
  89286. }
  89287. optimizer.start();
  89288. return optimizer;
  89289. };
  89290. return SceneOptimizer;
  89291. }());
  89292. BABYLON.SceneOptimizer = SceneOptimizer;
  89293. })(BABYLON || (BABYLON = {}));
  89294. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  89295. var BABYLON;
  89296. (function (BABYLON) {
  89297. var OutlineRenderer = /** @class */ (function () {
  89298. function OutlineRenderer(scene) {
  89299. this.zOffset = 1;
  89300. this._scene = scene;
  89301. }
  89302. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  89303. var _this = this;
  89304. if (useOverlay === void 0) { useOverlay = false; }
  89305. var scene = this._scene;
  89306. var engine = this._scene.getEngine();
  89307. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89308. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  89309. return;
  89310. }
  89311. var mesh = subMesh.getRenderingMesh();
  89312. var material = subMesh.getMaterial();
  89313. if (!material || !scene.activeCamera) {
  89314. return;
  89315. }
  89316. engine.enableEffect(this._effect);
  89317. // Logarithmic depth
  89318. if (material.useLogarithmicDepth) {
  89319. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  89320. }
  89321. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  89322. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  89323. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  89324. // Bones
  89325. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89326. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89327. }
  89328. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  89329. // Alpha test
  89330. if (material && material.needAlphaTesting()) {
  89331. var alphaTexture = material.getAlphaTestTexture();
  89332. if (alphaTexture) {
  89333. this._effect.setTexture("diffuseSampler", alphaTexture);
  89334. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89335. }
  89336. }
  89337. engine.setZOffset(-this.zOffset);
  89338. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  89339. engine.setZOffset(0);
  89340. };
  89341. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  89342. var defines = [];
  89343. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89344. var mesh = subMesh.getMesh();
  89345. var material = subMesh.getMaterial();
  89346. if (material) {
  89347. // Alpha test
  89348. if (material.needAlphaTesting()) {
  89349. defines.push("#define ALPHATEST");
  89350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89351. attribs.push(BABYLON.VertexBuffer.UVKind);
  89352. defines.push("#define UV1");
  89353. }
  89354. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89355. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89356. defines.push("#define UV2");
  89357. }
  89358. }
  89359. //Logarithmic depth
  89360. if (material.useLogarithmicDepth) {
  89361. defines.push("#define LOGARITHMICDEPTH");
  89362. }
  89363. }
  89364. // Bones
  89365. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89368. if (mesh.numBoneInfluencers > 4) {
  89369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89371. }
  89372. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89373. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  89374. }
  89375. else {
  89376. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89377. }
  89378. // Instances
  89379. if (useInstances) {
  89380. defines.push("#define INSTANCES");
  89381. attribs.push("world0");
  89382. attribs.push("world1");
  89383. attribs.push("world2");
  89384. attribs.push("world3");
  89385. }
  89386. // Get correct effect
  89387. var join = defines.join("\n");
  89388. if (this._cachedDefines !== join) {
  89389. this._cachedDefines = join;
  89390. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  89391. }
  89392. return this._effect.isReady();
  89393. };
  89394. return OutlineRenderer;
  89395. }());
  89396. BABYLON.OutlineRenderer = OutlineRenderer;
  89397. })(BABYLON || (BABYLON = {}));
  89398. //# sourceMappingURL=babylon.outlineRenderer.js.map
  89399. var BABYLON;
  89400. (function (BABYLON) {
  89401. var FaceAdjacencies = /** @class */ (function () {
  89402. function FaceAdjacencies() {
  89403. this.edges = new Array();
  89404. this.edgesConnectedCount = 0;
  89405. }
  89406. return FaceAdjacencies;
  89407. }());
  89408. var EdgesRenderer = /** @class */ (function () {
  89409. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  89410. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  89411. if (epsilon === void 0) { epsilon = 0.95; }
  89412. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  89413. this.edgesWidthScalerForOrthographic = 1000.0;
  89414. this.edgesWidthScalerForPerspective = 50.0;
  89415. this._linesPositions = new Array();
  89416. this._linesNormals = new Array();
  89417. this._linesIndices = new Array();
  89418. this._buffers = {};
  89419. this._checkVerticesInsteadOfIndices = false;
  89420. this._source = source;
  89421. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  89422. this._epsilon = epsilon;
  89423. this._prepareRessources();
  89424. this._generateEdgesLines();
  89425. }
  89426. EdgesRenderer.prototype._prepareRessources = function () {
  89427. if (this._lineShader) {
  89428. return;
  89429. }
  89430. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  89431. attributes: ["position", "normal"],
  89432. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  89433. });
  89434. this._lineShader.disableDepthWrite = true;
  89435. this._lineShader.backFaceCulling = false;
  89436. };
  89437. EdgesRenderer.prototype._rebuild = function () {
  89438. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89439. if (buffer) {
  89440. buffer._rebuild();
  89441. }
  89442. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89443. if (buffer) {
  89444. buffer._rebuild();
  89445. }
  89446. var scene = this._source.getScene();
  89447. var engine = scene.getEngine();
  89448. this._ib = engine.createIndexBuffer(this._linesIndices);
  89449. };
  89450. EdgesRenderer.prototype.dispose = function () {
  89451. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89452. if (buffer) {
  89453. buffer.dispose();
  89454. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  89455. }
  89456. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89457. if (buffer) {
  89458. buffer.dispose();
  89459. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  89460. }
  89461. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  89462. this._lineShader.dispose();
  89463. };
  89464. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  89465. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  89466. return 0;
  89467. }
  89468. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  89469. return 1;
  89470. }
  89471. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  89472. return 2;
  89473. }
  89474. return -1;
  89475. };
  89476. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  89477. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  89478. return 0;
  89479. }
  89480. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  89481. return 1;
  89482. }
  89483. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  89484. return 2;
  89485. }
  89486. return -1;
  89487. };
  89488. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  89489. var needToCreateLine;
  89490. if (edge === undefined) {
  89491. needToCreateLine = true;
  89492. }
  89493. else {
  89494. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  89495. needToCreateLine = dotProduct < this._epsilon;
  89496. }
  89497. if (needToCreateLine) {
  89498. var offset = this._linesPositions.length / 3;
  89499. var normal = p0.subtract(p1);
  89500. normal.normalize();
  89501. // Positions
  89502. this._linesPositions.push(p0.x);
  89503. this._linesPositions.push(p0.y);
  89504. this._linesPositions.push(p0.z);
  89505. this._linesPositions.push(p0.x);
  89506. this._linesPositions.push(p0.y);
  89507. this._linesPositions.push(p0.z);
  89508. this._linesPositions.push(p1.x);
  89509. this._linesPositions.push(p1.y);
  89510. this._linesPositions.push(p1.z);
  89511. this._linesPositions.push(p1.x);
  89512. this._linesPositions.push(p1.y);
  89513. this._linesPositions.push(p1.z);
  89514. // Normals
  89515. this._linesNormals.push(p1.x);
  89516. this._linesNormals.push(p1.y);
  89517. this._linesNormals.push(p1.z);
  89518. this._linesNormals.push(-1);
  89519. this._linesNormals.push(p1.x);
  89520. this._linesNormals.push(p1.y);
  89521. this._linesNormals.push(p1.z);
  89522. this._linesNormals.push(1);
  89523. this._linesNormals.push(p0.x);
  89524. this._linesNormals.push(p0.y);
  89525. this._linesNormals.push(p0.z);
  89526. this._linesNormals.push(-1);
  89527. this._linesNormals.push(p0.x);
  89528. this._linesNormals.push(p0.y);
  89529. this._linesNormals.push(p0.z);
  89530. this._linesNormals.push(1);
  89531. // Indices
  89532. this._linesIndices.push(offset);
  89533. this._linesIndices.push(offset + 1);
  89534. this._linesIndices.push(offset + 2);
  89535. this._linesIndices.push(offset);
  89536. this._linesIndices.push(offset + 2);
  89537. this._linesIndices.push(offset + 3);
  89538. }
  89539. };
  89540. EdgesRenderer.prototype._generateEdgesLines = function () {
  89541. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89542. var indices = this._source.getIndices();
  89543. if (!indices || !positions) {
  89544. return;
  89545. }
  89546. // First let's find adjacencies
  89547. var adjacencies = new Array();
  89548. var faceNormals = new Array();
  89549. var index;
  89550. var faceAdjacencies;
  89551. // Prepare faces
  89552. for (index = 0; index < indices.length; index += 3) {
  89553. faceAdjacencies = new FaceAdjacencies();
  89554. var p0Index = indices[index];
  89555. var p1Index = indices[index + 1];
  89556. var p2Index = indices[index + 2];
  89557. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  89558. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  89559. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  89560. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  89561. faceNormal.normalize();
  89562. faceNormals.push(faceNormal);
  89563. adjacencies.push(faceAdjacencies);
  89564. }
  89565. // Scan
  89566. for (index = 0; index < adjacencies.length; index++) {
  89567. faceAdjacencies = adjacencies[index];
  89568. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  89569. var otherFaceAdjacencies = adjacencies[otherIndex];
  89570. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  89571. break;
  89572. }
  89573. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  89574. continue;
  89575. }
  89576. var otherP0 = indices[otherIndex * 3];
  89577. var otherP1 = indices[otherIndex * 3 + 1];
  89578. var otherP2 = indices[otherIndex * 3 + 2];
  89579. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  89580. var otherEdgeIndex = 0;
  89581. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  89582. continue;
  89583. }
  89584. switch (edgeIndex) {
  89585. case 0:
  89586. if (this._checkVerticesInsteadOfIndices) {
  89587. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89588. }
  89589. else {
  89590. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89591. }
  89592. break;
  89593. case 1:
  89594. if (this._checkVerticesInsteadOfIndices) {
  89595. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89596. }
  89597. else {
  89598. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89599. }
  89600. break;
  89601. case 2:
  89602. if (this._checkVerticesInsteadOfIndices) {
  89603. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89604. }
  89605. else {
  89606. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89607. }
  89608. break;
  89609. }
  89610. if (otherEdgeIndex === -1) {
  89611. continue;
  89612. }
  89613. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89614. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89615. faceAdjacencies.edgesConnectedCount++;
  89616. otherFaceAdjacencies.edgesConnectedCount++;
  89617. if (faceAdjacencies.edgesConnectedCount === 3) {
  89618. break;
  89619. }
  89620. }
  89621. }
  89622. }
  89623. // Create lines
  89624. for (index = 0; index < adjacencies.length; index++) {
  89625. // 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
  89626. var current = adjacencies[index];
  89627. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89628. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89629. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89630. }
  89631. // Merge into a single mesh
  89632. var engine = this._source.getScene().getEngine();
  89633. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89634. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89635. this._ib = engine.createIndexBuffer(this._linesIndices);
  89636. this._indicesCount = this._linesIndices.length;
  89637. };
  89638. EdgesRenderer.prototype.render = function () {
  89639. var scene = this._source.getScene();
  89640. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89641. return;
  89642. }
  89643. var engine = scene.getEngine();
  89644. this._lineShader._preBind();
  89645. // VBOs
  89646. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89647. scene.resetCachedMaterial();
  89648. this._lineShader.setColor4("color", this._source.edgesColor);
  89649. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89650. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89651. }
  89652. else {
  89653. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89654. }
  89655. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89656. this._lineShader.bind(this._source.getWorldMatrix());
  89657. // Draw order
  89658. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89659. this._lineShader.unbind();
  89660. engine.setDepthWrite(true);
  89661. };
  89662. return EdgesRenderer;
  89663. }());
  89664. BABYLON.EdgesRenderer = EdgesRenderer;
  89665. })(BABYLON || (BABYLON = {}));
  89666. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89667. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89668. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89669. s = arguments[i];
  89670. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89671. t[p] = s[p];
  89672. }
  89673. return t;
  89674. };
  89675. var BABYLON;
  89676. (function (BABYLON) {
  89677. /**
  89678. * The effect layer Helps adding post process effect blended with the main pass.
  89679. *
  89680. * This can be for instance use to generate glow or higlight effects on the scene.
  89681. *
  89682. * The effect layer class can not be used directly and is intented to inherited from to be
  89683. * customized per effects.
  89684. */
  89685. var EffectLayer = /** @class */ (function () {
  89686. /**
  89687. * Instantiates a new effect Layer and references it in the scene.
  89688. * @param name The name of the layer
  89689. * @param scene The scene to use the layer in
  89690. */
  89691. function EffectLayer(
  89692. /** The Friendly of the effect in the scene */
  89693. name, scene) {
  89694. this._vertexBuffers = {};
  89695. this._maxSize = 0;
  89696. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89697. this._shouldRender = true;
  89698. this._postProcesses = [];
  89699. this._textures = [];
  89700. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89701. /**
  89702. * The clear color of the texture used to generate the glow map.
  89703. */
  89704. this.neutralColor = new BABYLON.Color4();
  89705. /**
  89706. * Specifies wether the highlight layer is enabled or not.
  89707. */
  89708. this.isEnabled = true;
  89709. /**
  89710. * An event triggered when the effect layer has been disposed.
  89711. */
  89712. this.onDisposeObservable = new BABYLON.Observable();
  89713. /**
  89714. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89715. */
  89716. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89717. /**
  89718. * An event triggered when the generated texture is being merged in the scene.
  89719. */
  89720. this.onBeforeComposeObservable = new BABYLON.Observable();
  89721. /**
  89722. * An event triggered when the generated texture has been merged in the scene.
  89723. */
  89724. this.onAfterComposeObservable = new BABYLON.Observable();
  89725. /**
  89726. * An event triggered when the efffect layer changes its size.
  89727. */
  89728. this.onSizeChangedObservable = new BABYLON.Observable();
  89729. this.name = name;
  89730. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89731. this._engine = scene.getEngine();
  89732. this._maxSize = this._engine.getCaps().maxTextureSize;
  89733. this._scene.effectLayers.push(this);
  89734. // Generate Buffers
  89735. this._generateIndexBuffer();
  89736. this._genrateVertexBuffer();
  89737. }
  89738. Object.defineProperty(EffectLayer.prototype, "camera", {
  89739. /**
  89740. * Gets the camera attached to the layer.
  89741. */
  89742. get: function () {
  89743. return this._effectLayerOptions.camera;
  89744. },
  89745. enumerable: true,
  89746. configurable: true
  89747. });
  89748. /**
  89749. * Initializes the effect layer with the required options.
  89750. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89751. */
  89752. EffectLayer.prototype._init = function (options) {
  89753. // Adapt options
  89754. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89755. this._setMainTextureSize();
  89756. this._createMainTexture();
  89757. this._createTextureAndPostProcesses();
  89758. this._mergeEffect = this._createMergeEffect();
  89759. };
  89760. /**
  89761. * Generates the index buffer of the full screen quad blending to the main canvas.
  89762. */
  89763. EffectLayer.prototype._generateIndexBuffer = function () {
  89764. // Indices
  89765. var indices = [];
  89766. indices.push(0);
  89767. indices.push(1);
  89768. indices.push(2);
  89769. indices.push(0);
  89770. indices.push(2);
  89771. indices.push(3);
  89772. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89773. };
  89774. /**
  89775. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89776. */
  89777. EffectLayer.prototype._genrateVertexBuffer = function () {
  89778. // VBO
  89779. var vertices = [];
  89780. vertices.push(1, 1);
  89781. vertices.push(-1, 1);
  89782. vertices.push(-1, -1);
  89783. vertices.push(1, -1);
  89784. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89786. };
  89787. /**
  89788. * Sets the main texture desired size which is the closest power of two
  89789. * of the engine canvas size.
  89790. */
  89791. EffectLayer.prototype._setMainTextureSize = function () {
  89792. if (this._effectLayerOptions.mainTextureFixedSize) {
  89793. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89794. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89795. }
  89796. else {
  89797. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89798. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89799. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89800. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89801. }
  89802. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89803. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89804. };
  89805. /**
  89806. * Creates the main texture for the effect layer.
  89807. */
  89808. EffectLayer.prototype._createMainTexture = function () {
  89809. var _this = this;
  89810. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89811. width: this._mainTextureDesiredSize.width,
  89812. height: this._mainTextureDesiredSize.height
  89813. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89814. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89815. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89816. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89817. this._mainTexture.anisotropicFilteringLevel = 1;
  89818. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89819. this._mainTexture.renderParticles = false;
  89820. this._mainTexture.renderList = null;
  89821. this._mainTexture.ignoreCameraViewport = true;
  89822. // Custom render function
  89823. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89824. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89825. var index;
  89826. var engine = _this._scene.getEngine();
  89827. if (depthOnlySubMeshes.length) {
  89828. engine.setColorWrite(false);
  89829. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89830. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89831. }
  89832. engine.setColorWrite(true);
  89833. }
  89834. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89835. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89836. }
  89837. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89838. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89839. }
  89840. for (index = 0; index < transparentSubMeshes.length; index++) {
  89841. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89842. }
  89843. };
  89844. this._mainTexture.onClearObservable.add(function (engine) {
  89845. engine.clear(_this.neutralColor, true, true, true);
  89846. });
  89847. };
  89848. /**
  89849. * Checks for the readiness of the element composing the layer.
  89850. * @param subMesh the mesh to check for
  89851. * @param useInstances specify wether or not to use instances to render the mesh
  89852. * @param emissiveTexture the associated emissive texture used to generate the glow
  89853. * @return true if ready otherwise, false
  89854. */
  89855. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89856. var material = subMesh.getMaterial();
  89857. if (!material) {
  89858. return false;
  89859. }
  89860. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89861. return false;
  89862. }
  89863. var defines = [];
  89864. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89865. var mesh = subMesh.getMesh();
  89866. var uv1 = false;
  89867. var uv2 = false;
  89868. // Alpha test
  89869. if (material && material.needAlphaTesting()) {
  89870. var alphaTexture = material.getAlphaTestTexture();
  89871. if (alphaTexture) {
  89872. defines.push("#define ALPHATEST");
  89873. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89874. alphaTexture.coordinatesIndex === 1) {
  89875. defines.push("#define DIFFUSEUV2");
  89876. uv2 = true;
  89877. }
  89878. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89879. defines.push("#define DIFFUSEUV1");
  89880. uv1 = true;
  89881. }
  89882. }
  89883. }
  89884. // Emissive
  89885. if (emissiveTexture) {
  89886. defines.push("#define EMISSIVE");
  89887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89888. emissiveTexture.coordinatesIndex === 1) {
  89889. defines.push("#define EMISSIVEUV2");
  89890. uv2 = true;
  89891. }
  89892. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89893. defines.push("#define EMISSIVEUV1");
  89894. uv1 = true;
  89895. }
  89896. }
  89897. if (uv1) {
  89898. attribs.push(BABYLON.VertexBuffer.UVKind);
  89899. defines.push("#define UV1");
  89900. }
  89901. if (uv2) {
  89902. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89903. defines.push("#define UV2");
  89904. }
  89905. // Bones
  89906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89909. if (mesh.numBoneInfluencers > 4) {
  89910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89912. }
  89913. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89914. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89915. }
  89916. else {
  89917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89918. }
  89919. // Morph targets
  89920. var manager = mesh.morphTargetManager;
  89921. var morphInfluencers = 0;
  89922. if (manager) {
  89923. if (manager.numInfluencers > 0) {
  89924. defines.push("#define MORPHTARGETS");
  89925. morphInfluencers = manager.numInfluencers;
  89926. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  89927. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  89928. }
  89929. }
  89930. // Instances
  89931. if (useInstances) {
  89932. defines.push("#define INSTANCES");
  89933. attribs.push("world0");
  89934. attribs.push("world1");
  89935. attribs.push("world2");
  89936. attribs.push("world3");
  89937. }
  89938. // Get correct effect
  89939. var join = defines.join("\n");
  89940. if (this._cachedDefines !== join) {
  89941. this._cachedDefines = join;
  89942. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  89943. }
  89944. return this._effectLayerMapGenerationEffect.isReady();
  89945. };
  89946. /**
  89947. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  89948. */
  89949. EffectLayer.prototype.render = function () {
  89950. var currentEffect = this._mergeEffect;
  89951. // Check
  89952. if (!currentEffect.isReady())
  89953. return;
  89954. for (var i = 0; i < this._postProcesses.length; i++) {
  89955. if (!this._postProcesses[i].isReady()) {
  89956. return;
  89957. }
  89958. }
  89959. var engine = this._scene.getEngine();
  89960. this.onBeforeComposeObservable.notifyObservers(this);
  89961. // Render
  89962. engine.enableEffect(currentEffect);
  89963. engine.setState(false);
  89964. // VBOs
  89965. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89966. // Cache
  89967. var previousAlphaMode = engine.getAlphaMode();
  89968. // Go Blend.
  89969. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  89970. // Blends the map on the main canvas.
  89971. this._internalRender(currentEffect);
  89972. // Restore Alpha
  89973. engine.setAlphaMode(previousAlphaMode);
  89974. this.onAfterComposeObservable.notifyObservers(this);
  89975. // Handle size changes.
  89976. var size = this._mainTexture.getSize();
  89977. this._setMainTextureSize();
  89978. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  89979. // Recreate RTT and post processes on size change.
  89980. this.onSizeChangedObservable.notifyObservers(this);
  89981. this._disposeTextureAndPostProcesses();
  89982. this._createMainTexture();
  89983. this._createTextureAndPostProcesses();
  89984. }
  89985. };
  89986. /**
  89987. * Determine if a given mesh will be used in the current effect.
  89988. * @param mesh mesh to test
  89989. * @returns true if the mesh will be used
  89990. */
  89991. EffectLayer.prototype.hasMesh = function (mesh) {
  89992. return true;
  89993. };
  89994. /**
  89995. * Returns true if the layer contains information to display, otherwise false.
  89996. * @returns true if the glow layer should be rendered
  89997. */
  89998. EffectLayer.prototype.shouldRender = function () {
  89999. return this.isEnabled && this._shouldRender;
  90000. };
  90001. /**
  90002. * Returns true if the mesh should render, otherwise false.
  90003. * @param mesh The mesh to render
  90004. * @returns true if it should render otherwise false
  90005. */
  90006. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90007. return true;
  90008. };
  90009. /**
  90010. * Returns true if the mesh should render, otherwise false.
  90011. * @param mesh The mesh to render
  90012. * @returns true if it should render otherwise false
  90013. */
  90014. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90015. return true;
  90016. };
  90017. /**
  90018. * Renders the submesh passed in parameter to the generation map.
  90019. */
  90020. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90021. var _this = this;
  90022. if (!this.shouldRender()) {
  90023. return;
  90024. }
  90025. var material = subMesh.getMaterial();
  90026. var mesh = subMesh.getRenderingMesh();
  90027. var scene = this._scene;
  90028. var engine = scene.getEngine();
  90029. if (!material) {
  90030. return;
  90031. }
  90032. // Do not block in blend mode.
  90033. if (material.needAlphaBlendingForMesh(mesh)) {
  90034. return;
  90035. }
  90036. // Culling
  90037. engine.setState(material.backFaceCulling);
  90038. // Managing instances
  90039. var batch = mesh._getInstancesRenderList(subMesh._id);
  90040. if (batch.mustReturn) {
  90041. return;
  90042. }
  90043. // Early Exit per mesh
  90044. if (!this._shouldRenderMesh(mesh)) {
  90045. return;
  90046. }
  90047. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90048. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90049. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90050. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90051. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90052. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90053. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90054. // Alpha test
  90055. if (material && material.needAlphaTesting()) {
  90056. var alphaTexture = material.getAlphaTestTexture();
  90057. if (alphaTexture) {
  90058. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90059. var textureMatrix = alphaTexture.getTextureMatrix();
  90060. if (textureMatrix) {
  90061. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90062. }
  90063. }
  90064. }
  90065. // Glow emissive only
  90066. if (this._emissiveTextureAndColor.texture) {
  90067. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90068. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90069. }
  90070. // Bones
  90071. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90072. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90073. }
  90074. // Morph targets
  90075. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90076. // Draw
  90077. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90078. }
  90079. else {
  90080. // Need to reset refresh rate of the shadowMap
  90081. this._mainTexture.resetRefreshCounter();
  90082. }
  90083. };
  90084. /**
  90085. * Rebuild the required buffers.
  90086. * @ignore Internal use only.
  90087. */
  90088. EffectLayer.prototype._rebuild = function () {
  90089. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90090. if (vb) {
  90091. vb._rebuild();
  90092. }
  90093. this._generateIndexBuffer();
  90094. };
  90095. /**
  90096. * Dispose only the render target textures and post process.
  90097. */
  90098. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90099. this._mainTexture.dispose();
  90100. for (var i = 0; i < this._postProcesses.length; i++) {
  90101. if (this._postProcesses[i]) {
  90102. this._postProcesses[i].dispose();
  90103. }
  90104. }
  90105. this._postProcesses = [];
  90106. for (var i = 0; i < this._textures.length; i++) {
  90107. if (this._textures[i]) {
  90108. this._textures[i].dispose();
  90109. }
  90110. }
  90111. this._textures = [];
  90112. };
  90113. /**
  90114. * Dispose the highlight layer and free resources.
  90115. */
  90116. EffectLayer.prototype.dispose = function () {
  90117. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90118. if (vertexBuffer) {
  90119. vertexBuffer.dispose();
  90120. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90121. }
  90122. if (this._indexBuffer) {
  90123. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90124. this._indexBuffer = null;
  90125. }
  90126. // Clean textures and post processes
  90127. this._disposeTextureAndPostProcesses();
  90128. // Remove from scene
  90129. var index = this._scene.effectLayers.indexOf(this, 0);
  90130. if (index > -1) {
  90131. this._scene.effectLayers.splice(index, 1);
  90132. }
  90133. // Callback
  90134. this.onDisposeObservable.notifyObservers(this);
  90135. this.onDisposeObservable.clear();
  90136. this.onBeforeRenderMainTextureObservable.clear();
  90137. this.onBeforeComposeObservable.clear();
  90138. this.onAfterComposeObservable.clear();
  90139. this.onSizeChangedObservable.clear();
  90140. };
  90141. /**
  90142. * Gets the class name of the effect layer
  90143. * @returns the string with the class name of the effect layer
  90144. */
  90145. EffectLayer.prototype.getClassName = function () {
  90146. return "EffectLayer";
  90147. };
  90148. /**
  90149. * Creates an effect layer from parsed effect layer data
  90150. * @param parsedEffectLayer defines effect layer data
  90151. * @param scene defines the current scene
  90152. * @param rootUrl defines the root URL containing the effect layer information
  90153. * @returns a parsed effect Layer
  90154. */
  90155. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90156. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90157. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90158. };
  90159. __decorate([
  90160. BABYLON.serialize()
  90161. ], EffectLayer.prototype, "name", void 0);
  90162. __decorate([
  90163. BABYLON.serializeAsColor4()
  90164. ], EffectLayer.prototype, "neutralColor", void 0);
  90165. __decorate([
  90166. BABYLON.serialize()
  90167. ], EffectLayer.prototype, "isEnabled", void 0);
  90168. __decorate([
  90169. BABYLON.serializeAsCameraReference()
  90170. ], EffectLayer.prototype, "camera", null);
  90171. return EffectLayer;
  90172. }());
  90173. BABYLON.EffectLayer = EffectLayer;
  90174. })(BABYLON || (BABYLON = {}));
  90175. //# sourceMappingURL=babylon.effectLayer.js.map
  90176. var BABYLON;
  90177. (function (BABYLON) {
  90178. /**
  90179. * Special Glow Blur post process only blurring the alpha channel
  90180. * It enforces keeping the most luminous color in the color channel.
  90181. */
  90182. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90183. __extends(GlowBlurPostProcess, _super);
  90184. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90186. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90187. _this.direction = direction;
  90188. _this.kernel = kernel;
  90189. _this.onApplyObservable.add(function (effect) {
  90190. effect.setFloat2("screenSize", _this.width, _this.height);
  90191. effect.setVector2("direction", _this.direction);
  90192. effect.setFloat("blurWidth", _this.kernel);
  90193. });
  90194. return _this;
  90195. }
  90196. return GlowBlurPostProcess;
  90197. }(BABYLON.PostProcess));
  90198. /**
  90199. * The highlight layer Helps adding a glow effect around a mesh.
  90200. *
  90201. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90202. * glowy meshes to your scene.
  90203. *
  90204. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90205. */
  90206. var HighlightLayer = /** @class */ (function (_super) {
  90207. __extends(HighlightLayer, _super);
  90208. /**
  90209. * Instantiates a new highlight Layer and references it to the scene..
  90210. * @param name The name of the layer
  90211. * @param scene The scene to use the layer in
  90212. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90213. */
  90214. function HighlightLayer(name, scene, options) {
  90215. var _this = _super.call(this, name, scene) || this;
  90216. _this.name = name;
  90217. /**
  90218. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90219. */
  90220. _this.innerGlow = true;
  90221. /**
  90222. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90223. */
  90224. _this.outerGlow = true;
  90225. /**
  90226. * An event triggered when the highlight layer is being blurred.
  90227. */
  90228. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90229. /**
  90230. * An event triggered when the highlight layer has been blurred.
  90231. */
  90232. _this.onAfterBlurObservable = new BABYLON.Observable();
  90233. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90234. _this._meshes = {};
  90235. _this._excludedMeshes = {};
  90236. _this.neutralColor = HighlightLayer.NeutralColor;
  90237. // Warn on stencil
  90238. if (!_this._engine.isStencilEnable) {
  90239. 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 }");
  90240. }
  90241. // Adapt options
  90242. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90243. // Initialize the layer
  90244. _this._init({
  90245. alphaBlendingMode: _this._options.alphaBlendingMode,
  90246. camera: _this._options.camera,
  90247. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90248. mainTextureRatio: _this._options.mainTextureRatio
  90249. });
  90250. // Do not render as long as no meshes have been added
  90251. _this._shouldRender = false;
  90252. return _this;
  90253. }
  90254. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90255. /**
  90256. * Gets the horizontal size of the blur.
  90257. */
  90258. get: function () {
  90259. return this._horizontalBlurPostprocess.kernel;
  90260. },
  90261. /**
  90262. * Specifies the horizontal size of the blur.
  90263. */
  90264. set: function (value) {
  90265. this._horizontalBlurPostprocess.kernel = value;
  90266. },
  90267. enumerable: true,
  90268. configurable: true
  90269. });
  90270. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90271. /**
  90272. * Gets the vertical size of the blur.
  90273. */
  90274. get: function () {
  90275. return this._verticalBlurPostprocess.kernel;
  90276. },
  90277. /**
  90278. * Specifies the vertical size of the blur.
  90279. */
  90280. set: function (value) {
  90281. this._verticalBlurPostprocess.kernel = value;
  90282. },
  90283. enumerable: true,
  90284. configurable: true
  90285. });
  90286. /**
  90287. * Get the effect name of the layer.
  90288. * @return The effect name
  90289. */
  90290. HighlightLayer.prototype.getEffectName = function () {
  90291. return HighlightLayer.EffectName;
  90292. };
  90293. /**
  90294. * Create the merge effect. This is the shader use to blit the information back
  90295. * to the main canvas at the end of the scene rendering.
  90296. */
  90297. HighlightLayer.prototype._createMergeEffect = function () {
  90298. // Effect
  90299. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  90300. };
  90301. /**
  90302. * Creates the render target textures and post processes used in the highlight layer.
  90303. */
  90304. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  90305. var _this = this;
  90306. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  90307. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  90308. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90309. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90310. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  90311. width: blurTextureWidth,
  90312. height: blurTextureHeight
  90313. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90314. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90315. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90316. this._blurTexture.anisotropicFilteringLevel = 16;
  90317. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90318. this._blurTexture.renderParticles = false;
  90319. this._blurTexture.ignoreCameraViewport = true;
  90320. this._textures = [this._blurTexture];
  90321. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  90322. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90323. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  90324. effect.setTexture("textureSampler", _this._mainTexture);
  90325. });
  90326. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90327. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90328. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90329. });
  90330. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90331. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  90332. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90333. });
  90334. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90335. }
  90336. else {
  90337. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  90338. width: blurTextureWidth,
  90339. height: blurTextureHeight
  90340. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90341. this._horizontalBlurPostprocess.width = blurTextureWidth;
  90342. this._horizontalBlurPostprocess.height = blurTextureHeight;
  90343. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90344. effect.setTexture("textureSampler", _this._mainTexture);
  90345. });
  90346. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  90347. width: blurTextureWidth,
  90348. height: blurTextureHeight
  90349. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90350. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90351. }
  90352. this._mainTexture.onAfterUnbindObservable.add(function () {
  90353. _this.onBeforeBlurObservable.notifyObservers(_this);
  90354. var internalTexture = _this._blurTexture.getInternalTexture();
  90355. if (internalTexture) {
  90356. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  90357. }
  90358. _this.onAfterBlurObservable.notifyObservers(_this);
  90359. });
  90360. // Prevent autoClear.
  90361. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90362. };
  90363. /**
  90364. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90365. */
  90366. HighlightLayer.prototype.needStencil = function () {
  90367. return true;
  90368. };
  90369. /**
  90370. * Checks for the readiness of the element composing the layer.
  90371. * @param subMesh the mesh to check for
  90372. * @param useInstances specify wether or not to use instances to render the mesh
  90373. * @param emissiveTexture the associated emissive texture used to generate the glow
  90374. * @return true if ready otherwise, false
  90375. */
  90376. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  90377. var material = subMesh.getMaterial();
  90378. var mesh = subMesh.getRenderingMesh();
  90379. if (!material || !mesh || !this._meshes) {
  90380. return false;
  90381. }
  90382. var emissiveTexture = null;
  90383. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90384. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90385. emissiveTexture = material.emissiveTexture;
  90386. }
  90387. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90388. };
  90389. /**
  90390. * Implementation specific of rendering the generating effect on the main canvas.
  90391. * @param effect The effect used to render through
  90392. */
  90393. HighlightLayer.prototype._internalRender = function (effect) {
  90394. // Texture
  90395. effect.setTexture("textureSampler", this._blurTexture);
  90396. // Cache
  90397. var engine = this._engine;
  90398. var previousStencilBuffer = engine.getStencilBuffer();
  90399. var previousStencilFunction = engine.getStencilFunction();
  90400. var previousStencilMask = engine.getStencilMask();
  90401. var previousStencilOperationPass = engine.getStencilOperationPass();
  90402. var previousStencilOperationFail = engine.getStencilOperationFail();
  90403. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  90404. var previousStencilReference = engine.getStencilFunctionReference();
  90405. // Stencil operations
  90406. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  90407. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  90408. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  90409. // Draw order
  90410. engine.setStencilMask(0x00);
  90411. engine.setStencilBuffer(true);
  90412. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  90413. // 2 passes inner outer
  90414. if (this.outerGlow) {
  90415. effect.setFloat("offset", 0);
  90416. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  90417. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90418. }
  90419. if (this.innerGlow) {
  90420. effect.setFloat("offset", 1);
  90421. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  90422. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90423. }
  90424. // Restore Cache
  90425. engine.setStencilFunction(previousStencilFunction);
  90426. engine.setStencilMask(previousStencilMask);
  90427. engine.setStencilBuffer(previousStencilBuffer);
  90428. engine.setStencilOperationPass(previousStencilOperationPass);
  90429. engine.setStencilOperationFail(previousStencilOperationFail);
  90430. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  90431. engine.setStencilFunctionReference(previousStencilReference);
  90432. };
  90433. /**
  90434. * Returns true if the layer contains information to display, otherwise false.
  90435. */
  90436. HighlightLayer.prototype.shouldRender = function () {
  90437. if (_super.prototype.shouldRender.call(this)) {
  90438. return this._meshes ? true : false;
  90439. }
  90440. return false;
  90441. };
  90442. /**
  90443. * Returns true if the mesh should render, otherwise false.
  90444. * @param mesh The mesh to render
  90445. * @returns true if it should render otherwise false
  90446. */
  90447. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  90448. // Excluded Mesh
  90449. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  90450. return false;
  90451. }
  90452. ;
  90453. return true;
  90454. };
  90455. /**
  90456. * Sets the required values for both the emissive texture and and the main color.
  90457. */
  90458. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90459. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90460. if (highlightLayerMesh) {
  90461. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  90462. }
  90463. else {
  90464. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90465. }
  90466. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90467. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90468. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  90469. }
  90470. else {
  90471. this._emissiveTextureAndColor.texture = null;
  90472. }
  90473. };
  90474. /**
  90475. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  90476. * @param mesh The mesh to exclude from the highlight layer
  90477. */
  90478. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  90479. if (!this._excludedMeshes) {
  90480. return;
  90481. }
  90482. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90483. if (!meshExcluded) {
  90484. this._excludedMeshes[mesh.uniqueId] = {
  90485. mesh: mesh,
  90486. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  90487. mesh.getEngine().setStencilBuffer(false);
  90488. }),
  90489. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  90490. mesh.getEngine().setStencilBuffer(true);
  90491. }),
  90492. };
  90493. }
  90494. };
  90495. /**
  90496. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  90497. * @param mesh The mesh to highlight
  90498. */
  90499. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  90500. if (!this._excludedMeshes) {
  90501. return;
  90502. }
  90503. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90504. if (meshExcluded) {
  90505. if (meshExcluded.beforeRender) {
  90506. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  90507. }
  90508. if (meshExcluded.afterRender) {
  90509. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  90510. }
  90511. }
  90512. this._excludedMeshes[mesh.uniqueId] = null;
  90513. };
  90514. /**
  90515. * Determine if a given mesh will be highlighted by the current HighlightLayer
  90516. * @param mesh mesh to test
  90517. * @returns true if the mesh will be highlighted by the current HighlightLayer
  90518. */
  90519. HighlightLayer.prototype.hasMesh = function (mesh) {
  90520. if (!this._meshes) {
  90521. return false;
  90522. }
  90523. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  90524. };
  90525. /**
  90526. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  90527. * @param mesh The mesh to highlight
  90528. * @param color The color of the highlight
  90529. * @param glowEmissiveOnly Extract the glow from the emissive texture
  90530. */
  90531. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  90532. var _this = this;
  90533. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  90534. if (!this._meshes) {
  90535. return;
  90536. }
  90537. var meshHighlight = this._meshes[mesh.uniqueId];
  90538. if (meshHighlight) {
  90539. meshHighlight.color = color;
  90540. }
  90541. else {
  90542. this._meshes[mesh.uniqueId] = {
  90543. mesh: mesh,
  90544. color: color,
  90545. // Lambda required for capture due to Observable this context
  90546. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  90547. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  90548. _this._defaultStencilReference(mesh);
  90549. }
  90550. else {
  90551. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  90552. }
  90553. }),
  90554. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  90555. glowEmissiveOnly: glowEmissiveOnly
  90556. };
  90557. }
  90558. this._shouldRender = true;
  90559. };
  90560. /**
  90561. * Remove a mesh from the highlight layer in order to make it stop glowing.
  90562. * @param mesh The mesh to highlight
  90563. */
  90564. HighlightLayer.prototype.removeMesh = function (mesh) {
  90565. if (!this._meshes) {
  90566. return;
  90567. }
  90568. var meshHighlight = this._meshes[mesh.uniqueId];
  90569. if (meshHighlight) {
  90570. if (meshHighlight.observerHighlight) {
  90571. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90572. }
  90573. if (meshHighlight.observerDefault) {
  90574. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90575. }
  90576. delete this._meshes[mesh.uniqueId];
  90577. }
  90578. this._shouldRender = false;
  90579. for (var meshHighlightToCheck in this._meshes) {
  90580. if (this._meshes[meshHighlightToCheck]) {
  90581. this._shouldRender = true;
  90582. break;
  90583. }
  90584. }
  90585. };
  90586. /**
  90587. * Force the stencil to the normal expected value for none glowing parts
  90588. */
  90589. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90590. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90591. };
  90592. /**
  90593. * Free any resources and references associated to a mesh.
  90594. * Internal use
  90595. * @param mesh The mesh to free.
  90596. */
  90597. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90598. this.removeMesh(mesh);
  90599. this.removeExcludedMesh(mesh);
  90600. };
  90601. /**
  90602. * Dispose the highlight layer and free resources.
  90603. */
  90604. HighlightLayer.prototype.dispose = function () {
  90605. if (this._meshes) {
  90606. // Clean mesh references
  90607. for (var id in this._meshes) {
  90608. var meshHighlight = this._meshes[id];
  90609. if (meshHighlight && meshHighlight.mesh) {
  90610. if (meshHighlight.observerHighlight) {
  90611. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90612. }
  90613. if (meshHighlight.observerDefault) {
  90614. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90615. }
  90616. }
  90617. }
  90618. this._meshes = null;
  90619. }
  90620. if (this._excludedMeshes) {
  90621. for (var id in this._excludedMeshes) {
  90622. var meshHighlight = this._excludedMeshes[id];
  90623. if (meshHighlight) {
  90624. if (meshHighlight.beforeRender) {
  90625. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90626. }
  90627. if (meshHighlight.afterRender) {
  90628. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90629. }
  90630. }
  90631. }
  90632. this._excludedMeshes = null;
  90633. }
  90634. _super.prototype.dispose.call(this);
  90635. };
  90636. /**
  90637. * Gets the class name of the effect layer
  90638. * @returns the string with the class name of the effect layer
  90639. */
  90640. HighlightLayer.prototype.getClassName = function () {
  90641. return "HighlightLayer";
  90642. };
  90643. /**
  90644. * Serializes this Highlight layer
  90645. * @returns a serialized Highlight layer object
  90646. */
  90647. HighlightLayer.prototype.serialize = function () {
  90648. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90649. serializationObject.customType = "BABYLON.HighlightLayer";
  90650. // Highlighted meshes
  90651. serializationObject.meshes = [];
  90652. if (this._meshes) {
  90653. for (var m in this._meshes) {
  90654. var mesh = this._meshes[m];
  90655. if (mesh) {
  90656. serializationObject.meshes.push({
  90657. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90658. color: mesh.color.asArray(),
  90659. meshId: mesh.mesh.id
  90660. });
  90661. }
  90662. }
  90663. }
  90664. // Excluded meshes
  90665. serializationObject.excludedMeshes = [];
  90666. if (this._excludedMeshes) {
  90667. for (var e in this._excludedMeshes) {
  90668. var excludedMesh = this._excludedMeshes[e];
  90669. if (excludedMesh) {
  90670. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90671. }
  90672. }
  90673. }
  90674. return serializationObject;
  90675. };
  90676. /**
  90677. * Creates a Highlight layer from parsed Highlight layer data
  90678. * @param parsedHightlightLayer defines the Highlight layer data
  90679. * @param scene defines the current scene
  90680. * @param rootUrl defines the root URL containing the Highlight layer information
  90681. * @returns a parsed Highlight layer
  90682. */
  90683. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90684. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90685. var index;
  90686. // Excluded meshes
  90687. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90688. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90689. if (mesh) {
  90690. hl.addExcludedMesh(mesh);
  90691. }
  90692. }
  90693. // Included meshes
  90694. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90695. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90696. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90697. if (mesh) {
  90698. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90699. }
  90700. }
  90701. return hl;
  90702. };
  90703. /**
  90704. * Effect Name of the highlight layer.
  90705. */
  90706. HighlightLayer.EffectName = "HighlightLayer";
  90707. /**
  90708. * The neutral color used during the preparation of the glow effect.
  90709. * This is black by default as the blend operation is a blend operation.
  90710. */
  90711. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90712. /**
  90713. * Stencil value used for glowing meshes.
  90714. */
  90715. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90716. /**
  90717. * Stencil value used for the other meshes in the scene.
  90718. */
  90719. HighlightLayer.NormalMeshStencilReference = 0x01;
  90720. __decorate([
  90721. BABYLON.serialize()
  90722. ], HighlightLayer.prototype, "innerGlow", void 0);
  90723. __decorate([
  90724. BABYLON.serialize()
  90725. ], HighlightLayer.prototype, "outerGlow", void 0);
  90726. __decorate([
  90727. BABYLON.serialize()
  90728. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90729. __decorate([
  90730. BABYLON.serialize()
  90731. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90732. __decorate([
  90733. BABYLON.serialize("options")
  90734. ], HighlightLayer.prototype, "_options", void 0);
  90735. return HighlightLayer;
  90736. }(BABYLON.EffectLayer));
  90737. BABYLON.HighlightLayer = HighlightLayer;
  90738. })(BABYLON || (BABYLON = {}));
  90739. //# sourceMappingURL=babylon.highlightLayer.js.map
  90740. var BABYLON;
  90741. (function (BABYLON) {
  90742. /**
  90743. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90744. *
  90745. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90746. * glowy meshes to your scene.
  90747. *
  90748. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90749. */
  90750. var GlowLayer = /** @class */ (function (_super) {
  90751. __extends(GlowLayer, _super);
  90752. /**
  90753. * Instantiates a new glow Layer and references it to the scene.
  90754. * @param name The name of the layer
  90755. * @param scene The scene to use the layer in
  90756. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90757. */
  90758. function GlowLayer(name, scene, options) {
  90759. var _this = _super.call(this, name, scene) || this;
  90760. _this._intensity = 1.0;
  90761. _this._includedOnlyMeshes = [];
  90762. _this._excludedMeshes = [];
  90763. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90764. // Adapt options
  90765. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90766. // Initialize the layer
  90767. _this._init({
  90768. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90769. camera: _this._options.camera,
  90770. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90771. mainTextureRatio: _this._options.mainTextureRatio
  90772. });
  90773. return _this;
  90774. }
  90775. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90776. /**
  90777. * Gets the kernel size of the blur.
  90778. */
  90779. get: function () {
  90780. return this._horizontalBlurPostprocess1.kernel;
  90781. },
  90782. /**
  90783. * Sets the kernel size of the blur.
  90784. */
  90785. set: function (value) {
  90786. this._horizontalBlurPostprocess1.kernel = value;
  90787. this._verticalBlurPostprocess1.kernel = value;
  90788. this._horizontalBlurPostprocess2.kernel = value;
  90789. this._verticalBlurPostprocess2.kernel = value;
  90790. },
  90791. enumerable: true,
  90792. configurable: true
  90793. });
  90794. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90795. /**
  90796. * Gets the glow intensity.
  90797. */
  90798. get: function () {
  90799. return this._intensity;
  90800. },
  90801. /**
  90802. * Sets the glow intensity.
  90803. */
  90804. set: function (value) {
  90805. this._intensity = value;
  90806. },
  90807. enumerable: true,
  90808. configurable: true
  90809. });
  90810. /**
  90811. * Get the effect name of the layer.
  90812. * @return The effect name
  90813. */
  90814. GlowLayer.prototype.getEffectName = function () {
  90815. return GlowLayer.EffectName;
  90816. };
  90817. /**
  90818. * Create the merge effect. This is the shader use to blit the information back
  90819. * to the main canvas at the end of the scene rendering.
  90820. */
  90821. GlowLayer.prototype._createMergeEffect = function () {
  90822. // Effect
  90823. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90824. };
  90825. /**
  90826. * Creates the render target textures and post processes used in the glow layer.
  90827. */
  90828. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90829. var _this = this;
  90830. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90831. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90832. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90833. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90834. var textureType = 0;
  90835. if (this._engine.getCaps().textureHalfFloatRender) {
  90836. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90837. }
  90838. else {
  90839. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90840. }
  90841. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90842. width: blurTextureWidth,
  90843. height: blurTextureHeight
  90844. }, this._scene, false, true, textureType);
  90845. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90846. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90847. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90848. this._blurTexture1.renderParticles = false;
  90849. this._blurTexture1.ignoreCameraViewport = true;
  90850. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90851. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90852. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90853. width: blurTextureWidth2,
  90854. height: blurTextureHeight2
  90855. }, this._scene, false, true, textureType);
  90856. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90857. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90858. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90859. this._blurTexture2.renderParticles = false;
  90860. this._blurTexture2.ignoreCameraViewport = true;
  90861. this._textures = [this._blurTexture1, this._blurTexture2];
  90862. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90863. width: blurTextureWidth,
  90864. height: blurTextureHeight
  90865. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90866. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90867. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90868. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90869. effect.setTexture("textureSampler", _this._mainTexture);
  90870. });
  90871. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90872. width: blurTextureWidth,
  90873. height: blurTextureHeight
  90874. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90875. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90876. width: blurTextureWidth2,
  90877. height: blurTextureHeight2
  90878. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90879. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  90880. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  90881. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  90882. effect.setTexture("textureSampler", _this._blurTexture1);
  90883. });
  90884. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90885. width: blurTextureWidth2,
  90886. height: blurTextureHeight2
  90887. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90888. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90889. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  90890. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90891. this._mainTexture.samples = this._options.mainTextureSamples;
  90892. this._mainTexture.onAfterUnbindObservable.add(function () {
  90893. var internalTexture = _this._blurTexture1.getInternalTexture();
  90894. if (internalTexture) {
  90895. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  90896. internalTexture = _this._blurTexture2.getInternalTexture();
  90897. if (internalTexture) {
  90898. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  90899. }
  90900. }
  90901. });
  90902. // Prevent autoClear.
  90903. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90904. };
  90905. /**
  90906. * Checks for the readiness of the element composing the layer.
  90907. * @param subMesh the mesh to check for
  90908. * @param useInstances specify wether or not to use instances to render the mesh
  90909. * @param emissiveTexture the associated emissive texture used to generate the glow
  90910. * @return true if ready otherwise, false
  90911. */
  90912. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  90913. var material = subMesh.getMaterial();
  90914. var mesh = subMesh.getRenderingMesh();
  90915. if (!material || !mesh) {
  90916. return false;
  90917. }
  90918. var emissiveTexture = material.emissiveTexture;
  90919. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90920. };
  90921. /**
  90922. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90923. */
  90924. GlowLayer.prototype.needStencil = function () {
  90925. return false;
  90926. };
  90927. /**
  90928. * Implementation specific of rendering the generating effect on the main canvas.
  90929. * @param effect The effect used to render through
  90930. */
  90931. GlowLayer.prototype._internalRender = function (effect) {
  90932. // Texture
  90933. effect.setTexture("textureSampler", this._blurTexture1);
  90934. effect.setTexture("textureSampler2", this._blurTexture2);
  90935. effect.setFloat("offset", this._intensity);
  90936. // Cache
  90937. var engine = this._engine;
  90938. var previousStencilBuffer = engine.getStencilBuffer();
  90939. // Draw order
  90940. engine.setStencilBuffer(false);
  90941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90942. // Draw order
  90943. engine.setStencilBuffer(previousStencilBuffer);
  90944. };
  90945. /**
  90946. * Sets the required values for both the emissive texture and and the main color.
  90947. */
  90948. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90949. var textureLevel = 1.0;
  90950. if (this.customEmissiveTextureSelector) {
  90951. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  90952. }
  90953. else {
  90954. if (material) {
  90955. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90956. if (this._emissiveTextureAndColor.texture) {
  90957. textureLevel = this._emissiveTextureAndColor.texture.level;
  90958. }
  90959. }
  90960. else {
  90961. this._emissiveTextureAndColor.texture = null;
  90962. }
  90963. }
  90964. if (this.customEmissiveColorSelector) {
  90965. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  90966. }
  90967. else {
  90968. if (material.emissiveColor) {
  90969. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  90970. }
  90971. else {
  90972. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90973. }
  90974. }
  90975. };
  90976. /**
  90977. * Returns true if the mesh should render, otherwise false.
  90978. * @param mesh The mesh to render
  90979. * @returns true if it should render otherwise false
  90980. */
  90981. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  90982. return this.hasMesh(mesh);
  90983. };
  90984. /**
  90985. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  90986. * @param mesh The mesh to exclude from the glow layer
  90987. */
  90988. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  90989. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  90990. this._excludedMeshes.push(mesh.uniqueId);
  90991. }
  90992. };
  90993. /**
  90994. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  90995. * @param mesh The mesh to remove
  90996. */
  90997. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  90998. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  90999. if (index !== -1) {
  91000. this._excludedMeshes.splice(index, 1);
  91001. }
  91002. };
  91003. /**
  91004. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91005. * @param mesh The mesh to include in the glow layer
  91006. */
  91007. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91008. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91009. this._includedOnlyMeshes.push(mesh.uniqueId);
  91010. }
  91011. };
  91012. /**
  91013. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91014. * @param mesh The mesh to remove
  91015. */
  91016. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91017. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91018. if (index !== -1) {
  91019. this._includedOnlyMeshes.splice(index, 1);
  91020. }
  91021. };
  91022. /**
  91023. * Determine if a given mesh will be used in the glow layer
  91024. * @param mesh The mesh to test
  91025. * @returns true if the mesh will be highlighted by the current glow layer
  91026. */
  91027. GlowLayer.prototype.hasMesh = function (mesh) {
  91028. // Included Mesh
  91029. if (this._includedOnlyMeshes.length) {
  91030. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91031. }
  91032. ;
  91033. // Excluded Mesh
  91034. if (this._excludedMeshes.length) {
  91035. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91036. }
  91037. ;
  91038. return true;
  91039. };
  91040. /**
  91041. * Free any resources and references associated to a mesh.
  91042. * Internal use
  91043. * @param mesh The mesh to free.
  91044. */
  91045. GlowLayer.prototype._disposeMesh = function (mesh) {
  91046. this.removeIncludedOnlyMesh(mesh);
  91047. this.removeExcludedMesh(mesh);
  91048. };
  91049. /**
  91050. * Gets the class name of the effect layer
  91051. * @returns the string with the class name of the effect layer
  91052. */
  91053. GlowLayer.prototype.getClassName = function () {
  91054. return "GlowLayer";
  91055. };
  91056. /**
  91057. * Serializes this glow layer
  91058. * @returns a serialized glow layer object
  91059. */
  91060. GlowLayer.prototype.serialize = function () {
  91061. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91062. serializationObject.customType = "BABYLON.GlowLayer";
  91063. var index;
  91064. // Included meshes
  91065. serializationObject.includedMeshes = [];
  91066. if (this._includedOnlyMeshes.length) {
  91067. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91068. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91069. if (mesh) {
  91070. serializationObject.includedMeshes.push(mesh.id);
  91071. }
  91072. }
  91073. }
  91074. // Excluded meshes
  91075. serializationObject.excludedMeshes = [];
  91076. if (this._excludedMeshes.length) {
  91077. for (index = 0; index < this._excludedMeshes.length; index++) {
  91078. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91079. if (mesh) {
  91080. serializationObject.excludedMeshes.push(mesh.id);
  91081. }
  91082. }
  91083. }
  91084. return serializationObject;
  91085. };
  91086. /**
  91087. * Creates a Glow Layer from parsed glow layer data
  91088. * @param parsedGlowLayer defines glow layer data
  91089. * @param scene defines the current scene
  91090. * @param rootUrl defines the root URL containing the glow layer information
  91091. * @returns a parsed Glow Layer
  91092. */
  91093. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91094. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91095. var index;
  91096. // Excluded meshes
  91097. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91098. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91099. if (mesh) {
  91100. gl.addExcludedMesh(mesh);
  91101. }
  91102. }
  91103. // Included meshes
  91104. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91105. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91106. if (mesh) {
  91107. gl.addIncludedOnlyMesh(mesh);
  91108. }
  91109. }
  91110. return gl;
  91111. };
  91112. /**
  91113. * Effect Name of the layer.
  91114. */
  91115. GlowLayer.EffectName = "GlowLayer";
  91116. /**
  91117. * The default blur kernel size used for the glow.
  91118. */
  91119. GlowLayer.DefaultBlurKernelSize = 32;
  91120. /**
  91121. * The default texture size ratio used for the glow.
  91122. */
  91123. GlowLayer.DefaultTextureRatio = 0.5;
  91124. __decorate([
  91125. BABYLON.serialize()
  91126. ], GlowLayer.prototype, "blurKernelSize", null);
  91127. __decorate([
  91128. BABYLON.serialize()
  91129. ], GlowLayer.prototype, "intensity", null);
  91130. __decorate([
  91131. BABYLON.serialize("options")
  91132. ], GlowLayer.prototype, "_options", void 0);
  91133. return GlowLayer;
  91134. }(BABYLON.EffectLayer));
  91135. BABYLON.GlowLayer = GlowLayer;
  91136. })(BABYLON || (BABYLON = {}));
  91137. //# sourceMappingURL=babylon.glowLayer.js.map
  91138. var BABYLON;
  91139. (function (BABYLON) {
  91140. /**
  91141. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91142. */
  91143. var AssetTaskState;
  91144. (function (AssetTaskState) {
  91145. /**
  91146. * Initialization
  91147. */
  91148. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91149. /**
  91150. * Running
  91151. */
  91152. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91153. /**
  91154. * Done
  91155. */
  91156. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91157. /**
  91158. * Error
  91159. */
  91160. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91161. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91162. /**
  91163. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91164. */
  91165. var AbstractAssetTask = /** @class */ (function () {
  91166. /**
  91167. * Creates a new {BABYLON.AssetsManager}
  91168. * @param name defines the name of the task
  91169. */
  91170. function AbstractAssetTask(
  91171. /**
  91172. * Task name
  91173. */ name) {
  91174. this.name = name;
  91175. this._isCompleted = false;
  91176. this._taskState = AssetTaskState.INIT;
  91177. }
  91178. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91179. /**
  91180. * Get if the task is completed
  91181. */
  91182. get: function () {
  91183. return this._isCompleted;
  91184. },
  91185. enumerable: true,
  91186. configurable: true
  91187. });
  91188. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91189. /**
  91190. * Gets the current state of the task
  91191. */
  91192. get: function () {
  91193. return this._taskState;
  91194. },
  91195. enumerable: true,
  91196. configurable: true
  91197. });
  91198. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91199. /**
  91200. * Gets the current error object (if task is in error)
  91201. */
  91202. get: function () {
  91203. return this._errorObject;
  91204. },
  91205. enumerable: true,
  91206. configurable: true
  91207. });
  91208. /**
  91209. * Internal only
  91210. * @ignore
  91211. */
  91212. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91213. if (this._errorObject) {
  91214. return;
  91215. }
  91216. this._errorObject = {
  91217. message: message,
  91218. exception: exception
  91219. };
  91220. };
  91221. /**
  91222. * Execute the current task
  91223. * @param scene defines the scene where you want your assets to be loaded
  91224. * @param onSuccess is a callback called when the task is successfully executed
  91225. * @param onError is a callback called if an error occurs
  91226. */
  91227. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91228. var _this = this;
  91229. this._taskState = AssetTaskState.RUNNING;
  91230. this.runTask(scene, function () {
  91231. _this.onDoneCallback(onSuccess, onError);
  91232. }, function (msg, exception) {
  91233. _this.onErrorCallback(onError, msg, exception);
  91234. });
  91235. };
  91236. /**
  91237. * Execute the current task
  91238. * @param scene defines the scene where you want your assets to be loaded
  91239. * @param onSuccess is a callback called when the task is successfully executed
  91240. * @param onError is a callback called if an error occurs
  91241. */
  91242. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91243. throw new Error("runTask is not implemented");
  91244. };
  91245. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91246. this._taskState = AssetTaskState.ERROR;
  91247. this._errorObject = {
  91248. message: message,
  91249. exception: exception
  91250. };
  91251. if (this.onError) {
  91252. this.onError(this, message, exception);
  91253. }
  91254. onError();
  91255. };
  91256. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91257. try {
  91258. this._taskState = AssetTaskState.DONE;
  91259. this._isCompleted = true;
  91260. if (this.onSuccess) {
  91261. this.onSuccess(this);
  91262. }
  91263. onSuccess();
  91264. }
  91265. catch (e) {
  91266. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91267. }
  91268. };
  91269. return AbstractAssetTask;
  91270. }());
  91271. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91272. /**
  91273. * Class used to share progress information about assets loading
  91274. */
  91275. var AssetsProgressEvent = /** @class */ (function () {
  91276. /**
  91277. * Creates a {BABYLON.AssetsProgressEvent}
  91278. * @param remainingCount defines the number of remaining tasks to process
  91279. * @param totalCount defines the total number of tasks
  91280. * @param task defines the task that was just processed
  91281. */
  91282. function AssetsProgressEvent(remainingCount, totalCount, task) {
  91283. this.remainingCount = remainingCount;
  91284. this.totalCount = totalCount;
  91285. this.task = task;
  91286. }
  91287. return AssetsProgressEvent;
  91288. }());
  91289. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  91290. /**
  91291. * Define a task used by {BABYLON.AssetsManager} to load meshes
  91292. */
  91293. var MeshAssetTask = /** @class */ (function (_super) {
  91294. __extends(MeshAssetTask, _super);
  91295. /**
  91296. * Creates a new {BABYLON.MeshAssetTask}
  91297. * @param name defines the name of the task
  91298. * @param meshesNames defines the list of mesh's names you want to load
  91299. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  91300. * @param sceneFilename defines the filename of the scene to load from
  91301. */
  91302. function MeshAssetTask(
  91303. /**
  91304. * Defines the name of the task
  91305. */
  91306. name,
  91307. /**
  91308. * Defines the list of mesh's names you want to load
  91309. */
  91310. meshesNames,
  91311. /**
  91312. * Defines the root url to use as a base to load your meshes and associated resources
  91313. */
  91314. rootUrl,
  91315. /**
  91316. * Defines the filename of the scene to load from
  91317. */
  91318. sceneFilename) {
  91319. var _this = _super.call(this, name) || this;
  91320. _this.name = name;
  91321. _this.meshesNames = meshesNames;
  91322. _this.rootUrl = rootUrl;
  91323. _this.sceneFilename = sceneFilename;
  91324. return _this;
  91325. }
  91326. /**
  91327. * Execute the current task
  91328. * @param scene defines the scene where you want your assets to be loaded
  91329. * @param onSuccess is a callback called when the task is successfully executed
  91330. * @param onError is a callback called if an error occurs
  91331. */
  91332. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91333. var _this = this;
  91334. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  91335. _this.loadedMeshes = meshes;
  91336. _this.loadedParticleSystems = particleSystems;
  91337. _this.loadedSkeletons = skeletons;
  91338. onSuccess();
  91339. }, null, function (scene, message, exception) {
  91340. onError(message, exception);
  91341. });
  91342. };
  91343. return MeshAssetTask;
  91344. }(AbstractAssetTask));
  91345. BABYLON.MeshAssetTask = MeshAssetTask;
  91346. /**
  91347. * Define a task used by {BABYLON.AssetsManager} to load text content
  91348. */
  91349. var TextFileAssetTask = /** @class */ (function (_super) {
  91350. __extends(TextFileAssetTask, _super);
  91351. /**
  91352. * Creates a new TextFileAssetTask object
  91353. * @param name defines the name of the task
  91354. * @param url defines the location of the file to load
  91355. */
  91356. function TextFileAssetTask(
  91357. /**
  91358. * Defines the name of the task
  91359. */
  91360. name,
  91361. /**
  91362. * Defines the location of the file to load
  91363. */
  91364. url) {
  91365. var _this = _super.call(this, name) || this;
  91366. _this.name = name;
  91367. _this.url = url;
  91368. return _this;
  91369. }
  91370. /**
  91371. * Execute the current task
  91372. * @param scene defines the scene where you want your assets to be loaded
  91373. * @param onSuccess is a callback called when the task is successfully executed
  91374. * @param onError is a callback called if an error occurs
  91375. */
  91376. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91377. var _this = this;
  91378. scene._loadFile(this.url, function (data) {
  91379. _this.text = data;
  91380. onSuccess();
  91381. }, undefined, false, false, function (request, exception) {
  91382. if (request) {
  91383. onError(request.status + " " + request.statusText, exception);
  91384. }
  91385. });
  91386. };
  91387. return TextFileAssetTask;
  91388. }(AbstractAssetTask));
  91389. BABYLON.TextFileAssetTask = TextFileAssetTask;
  91390. /**
  91391. * Define a task used by {BABYLON.AssetsManager} to load binary data
  91392. */
  91393. var BinaryFileAssetTask = /** @class */ (function (_super) {
  91394. __extends(BinaryFileAssetTask, _super);
  91395. /**
  91396. * Creates a new BinaryFileAssetTask object
  91397. * @param name defines the name of the new task
  91398. * @param url defines the location of the file to load
  91399. */
  91400. function BinaryFileAssetTask(
  91401. /**
  91402. * Defines the name of the task
  91403. */
  91404. name,
  91405. /**
  91406. * Defines the location of the file to load
  91407. */
  91408. url) {
  91409. var _this = _super.call(this, name) || this;
  91410. _this.name = name;
  91411. _this.url = url;
  91412. return _this;
  91413. }
  91414. /**
  91415. * Execute the current task
  91416. * @param scene defines the scene where you want your assets to be loaded
  91417. * @param onSuccess is a callback called when the task is successfully executed
  91418. * @param onError is a callback called if an error occurs
  91419. */
  91420. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91421. var _this = this;
  91422. scene._loadFile(this.url, function (data) {
  91423. _this.data = data;
  91424. onSuccess();
  91425. }, undefined, true, true, function (request, exception) {
  91426. if (request) {
  91427. onError(request.status + " " + request.statusText, exception);
  91428. }
  91429. });
  91430. };
  91431. return BinaryFileAssetTask;
  91432. }(AbstractAssetTask));
  91433. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  91434. /**
  91435. * Define a task used by {BABYLON.AssetsManager} to load images
  91436. */
  91437. var ImageAssetTask = /** @class */ (function (_super) {
  91438. __extends(ImageAssetTask, _super);
  91439. /**
  91440. * Creates a new ImageAssetTask
  91441. * @param name defines the name of the task
  91442. * @param url defines the location of the image to load
  91443. */
  91444. function ImageAssetTask(
  91445. /**
  91446. * Defines the name of the task
  91447. */
  91448. name,
  91449. /**
  91450. * Defines the location of the image to load
  91451. */
  91452. url) {
  91453. var _this = _super.call(this, name) || this;
  91454. _this.name = name;
  91455. _this.url = url;
  91456. return _this;
  91457. }
  91458. /**
  91459. * Execute the current task
  91460. * @param scene defines the scene where you want your assets to be loaded
  91461. * @param onSuccess is a callback called when the task is successfully executed
  91462. * @param onError is a callback called if an error occurs
  91463. */
  91464. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91465. var _this = this;
  91466. var img = new Image();
  91467. BABYLON.Tools.SetCorsBehavior(this.url, img);
  91468. img.onload = function () {
  91469. _this.image = img;
  91470. onSuccess();
  91471. };
  91472. img.onerror = function (err) {
  91473. onError("Error loading image", err);
  91474. };
  91475. img.src = this.url;
  91476. };
  91477. return ImageAssetTask;
  91478. }(AbstractAssetTask));
  91479. BABYLON.ImageAssetTask = ImageAssetTask;
  91480. /**
  91481. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  91482. */
  91483. var TextureAssetTask = /** @class */ (function (_super) {
  91484. __extends(TextureAssetTask, _super);
  91485. /**
  91486. * Creates a new TextureAssetTask object
  91487. * @param name defines the name of the task
  91488. * @param url defines the location of the file to load
  91489. * @param noMipmap defines if mipmap should not be generated (default is false)
  91490. * @param invertY defines if texture must be inverted on Y axis (default is false)
  91491. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91492. */
  91493. function TextureAssetTask(
  91494. /**
  91495. * Defines the name of the task
  91496. */
  91497. name,
  91498. /**
  91499. * Defines the location of the file to load
  91500. */
  91501. url,
  91502. /**
  91503. * Defines if mipmap should not be generated (default is false)
  91504. */
  91505. noMipmap,
  91506. /**
  91507. * Defines if texture must be inverted on Y axis (default is false)
  91508. */
  91509. invertY,
  91510. /**
  91511. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91512. */
  91513. samplingMode) {
  91514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91515. var _this = _super.call(this, name) || this;
  91516. _this.name = name;
  91517. _this.url = url;
  91518. _this.noMipmap = noMipmap;
  91519. _this.invertY = invertY;
  91520. _this.samplingMode = samplingMode;
  91521. return _this;
  91522. }
  91523. /**
  91524. * Execute the current task
  91525. * @param scene defines the scene where you want your assets to be loaded
  91526. * @param onSuccess is a callback called when the task is successfully executed
  91527. * @param onError is a callback called if an error occurs
  91528. */
  91529. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91530. var onload = function () {
  91531. onSuccess();
  91532. };
  91533. var onerror = function (message, exception) {
  91534. onError(message, exception);
  91535. };
  91536. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  91537. };
  91538. return TextureAssetTask;
  91539. }(AbstractAssetTask));
  91540. BABYLON.TextureAssetTask = TextureAssetTask;
  91541. /**
  91542. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  91543. */
  91544. var CubeTextureAssetTask = /** @class */ (function (_super) {
  91545. __extends(CubeTextureAssetTask, _super);
  91546. /**
  91547. * Creates a new CubeTextureAssetTask
  91548. * @param name defines the name of the task
  91549. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91550. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91551. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91552. * @param files defines the explicit list of files (undefined by default)
  91553. */
  91554. function CubeTextureAssetTask(
  91555. /**
  91556. * Defines the name of the task
  91557. */
  91558. name,
  91559. /**
  91560. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91561. */
  91562. url,
  91563. /**
  91564. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91565. */
  91566. extensions,
  91567. /**
  91568. * Defines if mipmaps should not be generated (default is false)
  91569. */
  91570. noMipmap,
  91571. /**
  91572. * Defines the explicit list of files (undefined by default)
  91573. */
  91574. files) {
  91575. var _this = _super.call(this, name) || this;
  91576. _this.name = name;
  91577. _this.url = url;
  91578. _this.extensions = extensions;
  91579. _this.noMipmap = noMipmap;
  91580. _this.files = files;
  91581. return _this;
  91582. }
  91583. /**
  91584. * Execute the current task
  91585. * @param scene defines the scene where you want your assets to be loaded
  91586. * @param onSuccess is a callback called when the task is successfully executed
  91587. * @param onError is a callback called if an error occurs
  91588. */
  91589. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91590. var onload = function () {
  91591. onSuccess();
  91592. };
  91593. var onerror = function (message, exception) {
  91594. onError(message, exception);
  91595. };
  91596. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91597. };
  91598. return CubeTextureAssetTask;
  91599. }(AbstractAssetTask));
  91600. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91601. /**
  91602. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91603. */
  91604. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91605. __extends(HDRCubeTextureAssetTask, _super);
  91606. /**
  91607. * Creates a new HDRCubeTextureAssetTask object
  91608. * @param name defines the name of the task
  91609. * @param url defines the location of the file to load
  91610. * @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.
  91611. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91612. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91613. * @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)
  91614. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91615. */
  91616. function HDRCubeTextureAssetTask(
  91617. /**
  91618. * Defines the name of the task
  91619. */
  91620. name,
  91621. /**
  91622. * Defines the location of the file to load
  91623. */
  91624. url,
  91625. /**
  91626. * 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.
  91627. */
  91628. size,
  91629. /**
  91630. * Defines if mipmaps should not be generated (default is false)
  91631. */
  91632. noMipmap,
  91633. /**
  91634. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91635. */
  91636. generateHarmonics,
  91637. /**
  91638. * 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)
  91639. */
  91640. useInGammaSpace,
  91641. /**
  91642. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91643. */
  91644. usePMREMGenerator) {
  91645. if (noMipmap === void 0) { noMipmap = false; }
  91646. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91647. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91648. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91649. var _this = _super.call(this, name) || this;
  91650. _this.name = name;
  91651. _this.url = url;
  91652. _this.size = size;
  91653. _this.noMipmap = noMipmap;
  91654. _this.generateHarmonics = generateHarmonics;
  91655. _this.useInGammaSpace = useInGammaSpace;
  91656. _this.usePMREMGenerator = usePMREMGenerator;
  91657. return _this;
  91658. }
  91659. /**
  91660. * Execute the current task
  91661. * @param scene defines the scene where you want your assets to be loaded
  91662. * @param onSuccess is a callback called when the task is successfully executed
  91663. * @param onError is a callback called if an error occurs
  91664. */
  91665. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91666. var onload = function () {
  91667. onSuccess();
  91668. };
  91669. var onerror = function (message, exception) {
  91670. onError(message, exception);
  91671. };
  91672. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91673. };
  91674. return HDRCubeTextureAssetTask;
  91675. }(AbstractAssetTask));
  91676. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91677. /**
  91678. * This class can be used to easily import assets into a scene
  91679. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91680. */
  91681. var AssetsManager = /** @class */ (function () {
  91682. /**
  91683. * Creates a new AssetsManager
  91684. * @param scene defines the scene to work on
  91685. */
  91686. function AssetsManager(scene) {
  91687. this._isLoading = false;
  91688. this._tasks = new Array();
  91689. this._waitingTasksCount = 0;
  91690. this._totalTasksCount = 0;
  91691. /**
  91692. * Observable called when all tasks are processed
  91693. */
  91694. this.onTaskSuccessObservable = new BABYLON.Observable();
  91695. /**
  91696. * Observable called when a task had an error
  91697. */
  91698. this.onTaskErrorObservable = new BABYLON.Observable();
  91699. /**
  91700. * Observable called when a task is successful
  91701. */
  91702. this.onTasksDoneObservable = new BABYLON.Observable();
  91703. /**
  91704. * Observable called when a task is done (whatever the result is)
  91705. */
  91706. this.onProgressObservable = new BABYLON.Observable();
  91707. /**
  91708. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91709. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91710. */
  91711. this.useDefaultLoadingScreen = true;
  91712. this._scene = scene;
  91713. }
  91714. /**
  91715. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91716. * @param taskName defines the name of the new task
  91717. * @param meshesNames defines the name of meshes to load
  91718. * @param rootUrl defines the root url to use to locate files
  91719. * @param sceneFilename defines the filename of the scene file
  91720. * @returns a new {BABYLON.MeshAssetTask} object
  91721. */
  91722. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91723. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91724. this._tasks.push(task);
  91725. return task;
  91726. };
  91727. /**
  91728. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91729. * @param taskName defines the name of the new task
  91730. * @param url defines the url of the file to load
  91731. * @returns a new {BABYLON.TextFileAssetTask} object
  91732. */
  91733. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91734. var task = new TextFileAssetTask(taskName, url);
  91735. this._tasks.push(task);
  91736. return task;
  91737. };
  91738. /**
  91739. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91740. * @param taskName defines the name of the new task
  91741. * @param url defines the url of the file to load
  91742. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91743. */
  91744. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91745. var task = new BinaryFileAssetTask(taskName, url);
  91746. this._tasks.push(task);
  91747. return task;
  91748. };
  91749. /**
  91750. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91751. * @param taskName defines the name of the new task
  91752. * @param url defines the url of the file to load
  91753. * @returns a new {BABYLON.ImageAssetTask} object
  91754. */
  91755. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91756. var task = new ImageAssetTask(taskName, url);
  91757. this._tasks.push(task);
  91758. return task;
  91759. };
  91760. /**
  91761. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91762. * @param taskName defines the name of the new task
  91763. * @param url defines the url of the file to load
  91764. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91765. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91766. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91767. * @returns a new {BABYLON.TextureAssetTask} object
  91768. */
  91769. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91771. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91772. this._tasks.push(task);
  91773. return task;
  91774. };
  91775. /**
  91776. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91777. * @param taskName defines the name of the new task
  91778. * @param url defines the url of the file to load
  91779. * @param extensions defines the extension to use to load the cube map (can be null)
  91780. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91781. * @param files defines the list of files to load (can be null)
  91782. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91783. */
  91784. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91785. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91786. this._tasks.push(task);
  91787. return task;
  91788. };
  91789. /**
  91790. *
  91791. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91792. * @param taskName defines the name of the new task
  91793. * @param url defines the url of the file to load
  91794. * @param size defines the size you want for the cubemap (can be null)
  91795. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91796. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91797. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91798. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91799. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91800. */
  91801. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91802. if (noMipmap === void 0) { noMipmap = false; }
  91803. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91804. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91805. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91806. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91807. this._tasks.push(task);
  91808. return task;
  91809. };
  91810. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91811. var _this = this;
  91812. this._waitingTasksCount--;
  91813. try {
  91814. if (task.taskState === AssetTaskState.DONE) {
  91815. // Let's remove successfull tasks
  91816. BABYLON.Tools.SetImmediate(function () {
  91817. var index = _this._tasks.indexOf(task);
  91818. if (index > -1) {
  91819. _this._tasks.splice(index, 1);
  91820. }
  91821. });
  91822. }
  91823. if (this.onProgress) {
  91824. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91825. }
  91826. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91827. }
  91828. catch (e) {
  91829. BABYLON.Tools.Error("Error running progress callbacks.");
  91830. console.log(e);
  91831. }
  91832. if (this._waitingTasksCount === 0) {
  91833. try {
  91834. if (this.onFinish) {
  91835. this.onFinish(this._tasks);
  91836. }
  91837. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91838. }
  91839. catch (e) {
  91840. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91841. console.log(e);
  91842. }
  91843. this._isLoading = false;
  91844. this._scene.getEngine().hideLoadingUI();
  91845. }
  91846. };
  91847. AssetsManager.prototype._runTask = function (task) {
  91848. var _this = this;
  91849. var done = function () {
  91850. try {
  91851. if (_this.onTaskSuccess) {
  91852. _this.onTaskSuccess(task);
  91853. }
  91854. _this.onTaskSuccessObservable.notifyObservers(task);
  91855. _this._decreaseWaitingTasksCount(task);
  91856. }
  91857. catch (e) {
  91858. error("Error executing task success callbacks", e);
  91859. }
  91860. };
  91861. var error = function (message, exception) {
  91862. task._setErrorObject(message, exception);
  91863. if (_this.onTaskError) {
  91864. _this.onTaskError(task);
  91865. }
  91866. _this.onTaskErrorObservable.notifyObservers(task);
  91867. _this._decreaseWaitingTasksCount(task);
  91868. };
  91869. task.run(this._scene, done, error);
  91870. };
  91871. /**
  91872. * Reset the {BABYLON.AssetsManager} and remove all tasks
  91873. * @return the current instance of the {BABYLON.AssetsManager}
  91874. */
  91875. AssetsManager.prototype.reset = function () {
  91876. this._isLoading = false;
  91877. this._tasks = new Array();
  91878. return this;
  91879. };
  91880. /**
  91881. * Start the loading process
  91882. * @return the current instance of the {BABYLON.AssetsManager}
  91883. */
  91884. AssetsManager.prototype.load = function () {
  91885. if (this._isLoading) {
  91886. return this;
  91887. }
  91888. this._isLoading = true;
  91889. this._waitingTasksCount = this._tasks.length;
  91890. this._totalTasksCount = this._tasks.length;
  91891. if (this._waitingTasksCount === 0) {
  91892. this._isLoading = false;
  91893. if (this.onFinish) {
  91894. this.onFinish(this._tasks);
  91895. }
  91896. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91897. return this;
  91898. }
  91899. if (this.useDefaultLoadingScreen) {
  91900. this._scene.getEngine().displayLoadingUI();
  91901. }
  91902. for (var index = 0; index < this._tasks.length; index++) {
  91903. var task = this._tasks[index];
  91904. this._runTask(task);
  91905. }
  91906. return this;
  91907. };
  91908. return AssetsManager;
  91909. }());
  91910. BABYLON.AssetsManager = AssetsManager;
  91911. })(BABYLON || (BABYLON = {}));
  91912. //# sourceMappingURL=babylon.assetsManager.js.map
  91913. var BABYLON;
  91914. (function (BABYLON) {
  91915. var serializedGeometries = [];
  91916. var serializeGeometry = function (geometry, serializationGeometries) {
  91917. if (serializedGeometries[geometry.id]) {
  91918. return;
  91919. }
  91920. if (geometry.doNotSerialize) {
  91921. return;
  91922. }
  91923. if (geometry instanceof BABYLON.BoxGeometry) {
  91924. serializationGeometries.boxes.push(geometry.serialize());
  91925. }
  91926. else if (geometry instanceof BABYLON.SphereGeometry) {
  91927. serializationGeometries.spheres.push(geometry.serialize());
  91928. }
  91929. else if (geometry instanceof BABYLON.CylinderGeometry) {
  91930. serializationGeometries.cylinders.push(geometry.serialize());
  91931. }
  91932. else if (geometry instanceof BABYLON.TorusGeometry) {
  91933. serializationGeometries.toruses.push(geometry.serialize());
  91934. }
  91935. else if (geometry instanceof BABYLON.GroundGeometry) {
  91936. serializationGeometries.grounds.push(geometry.serialize());
  91937. }
  91938. else if (geometry instanceof BABYLON.Plane) {
  91939. serializationGeometries.planes.push(geometry.serialize());
  91940. }
  91941. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  91942. serializationGeometries.torusKnots.push(geometry.serialize());
  91943. }
  91944. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  91945. throw new Error("Unknown primitive type");
  91946. }
  91947. else {
  91948. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  91949. }
  91950. serializedGeometries[geometry.id] = true;
  91951. };
  91952. var serializeMesh = function (mesh, serializationScene) {
  91953. var serializationObject = {};
  91954. // Geometry
  91955. var geometry = mesh._geometry;
  91956. if (geometry) {
  91957. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  91958. // 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
  91959. serializeGeometry(geometry, serializationScene.geometries);
  91960. }
  91961. }
  91962. // Custom
  91963. if (mesh.serialize) {
  91964. mesh.serialize(serializationObject);
  91965. }
  91966. return serializationObject;
  91967. };
  91968. var finalizeSingleMesh = function (mesh, serializationObject) {
  91969. //only works if the mesh is already loaded
  91970. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91971. //serialize material
  91972. if (mesh.material) {
  91973. if (mesh.material instanceof BABYLON.StandardMaterial) {
  91974. serializationObject.materials = serializationObject.materials || [];
  91975. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91976. serializationObject.materials.push(mesh.material.serialize());
  91977. }
  91978. }
  91979. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  91980. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  91981. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91982. serializationObject.multiMaterials.push(mesh.material.serialize());
  91983. }
  91984. }
  91985. }
  91986. //serialize geometry
  91987. var geometry = mesh._geometry;
  91988. if (geometry) {
  91989. if (!serializationObject.geometries) {
  91990. serializationObject.geometries = {};
  91991. serializationObject.geometries.boxes = [];
  91992. serializationObject.geometries.spheres = [];
  91993. serializationObject.geometries.cylinders = [];
  91994. serializationObject.geometries.toruses = [];
  91995. serializationObject.geometries.grounds = [];
  91996. serializationObject.geometries.planes = [];
  91997. serializationObject.geometries.torusKnots = [];
  91998. serializationObject.geometries.vertexData = [];
  91999. }
  92000. serializeGeometry(geometry, serializationObject.geometries);
  92001. }
  92002. // Skeletons
  92003. if (mesh.skeleton) {
  92004. serializationObject.skeletons = serializationObject.skeletons || [];
  92005. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92006. }
  92007. //serialize the actual mesh
  92008. serializationObject.meshes = serializationObject.meshes || [];
  92009. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92010. }
  92011. };
  92012. var SceneSerializer = /** @class */ (function () {
  92013. function SceneSerializer() {
  92014. }
  92015. SceneSerializer.ClearCache = function () {
  92016. serializedGeometries = [];
  92017. };
  92018. SceneSerializer.Serialize = function (scene) {
  92019. var serializationObject = {};
  92020. SceneSerializer.ClearCache();
  92021. // Scene
  92022. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92023. serializationObject.autoClear = scene.autoClear;
  92024. serializationObject.clearColor = scene.clearColor.asArray();
  92025. serializationObject.ambientColor = scene.ambientColor.asArray();
  92026. serializationObject.gravity = scene.gravity.asArray();
  92027. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92028. serializationObject.workerCollisions = scene.workerCollisions;
  92029. // Fog
  92030. if (scene.fogMode && scene.fogMode !== 0) {
  92031. serializationObject.fogMode = scene.fogMode;
  92032. serializationObject.fogColor = scene.fogColor.asArray();
  92033. serializationObject.fogStart = scene.fogStart;
  92034. serializationObject.fogEnd = scene.fogEnd;
  92035. serializationObject.fogDensity = scene.fogDensity;
  92036. }
  92037. //Physics
  92038. if (scene.isPhysicsEnabled()) {
  92039. var physicEngine = scene.getPhysicsEngine();
  92040. if (physicEngine) {
  92041. serializationObject.physicsEnabled = true;
  92042. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92043. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92044. }
  92045. }
  92046. // Metadata
  92047. if (scene.metadata) {
  92048. serializationObject.metadata = scene.metadata;
  92049. }
  92050. // Morph targets
  92051. serializationObject.morphTargetManagers = [];
  92052. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92053. var abstractMesh = _a[_i];
  92054. var manager = abstractMesh.morphTargetManager;
  92055. if (manager) {
  92056. serializationObject.morphTargetManagers.push(manager.serialize());
  92057. }
  92058. }
  92059. // Lights
  92060. serializationObject.lights = [];
  92061. var index;
  92062. var light;
  92063. for (index = 0; index < scene.lights.length; index++) {
  92064. light = scene.lights[index];
  92065. if (!light.doNotSerialize) {
  92066. serializationObject.lights.push(light.serialize());
  92067. }
  92068. }
  92069. // Cameras
  92070. serializationObject.cameras = [];
  92071. for (index = 0; index < scene.cameras.length; index++) {
  92072. var camera = scene.cameras[index];
  92073. if (!camera.doNotSerialize) {
  92074. serializationObject.cameras.push(camera.serialize());
  92075. }
  92076. }
  92077. if (scene.activeCamera) {
  92078. serializationObject.activeCameraID = scene.activeCamera.id;
  92079. }
  92080. // Animations
  92081. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92082. // Materials
  92083. serializationObject.materials = [];
  92084. serializationObject.multiMaterials = [];
  92085. var material;
  92086. for (index = 0; index < scene.materials.length; index++) {
  92087. material = scene.materials[index];
  92088. if (!material.doNotSerialize) {
  92089. serializationObject.materials.push(material.serialize());
  92090. }
  92091. }
  92092. // MultiMaterials
  92093. serializationObject.multiMaterials = [];
  92094. for (index = 0; index < scene.multiMaterials.length; index++) {
  92095. var multiMaterial = scene.multiMaterials[index];
  92096. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92097. }
  92098. // Environment texture
  92099. if (scene.environmentTexture) {
  92100. serializationObject.environmentTexture = scene.environmentTexture.name;
  92101. }
  92102. // Skeletons
  92103. serializationObject.skeletons = [];
  92104. for (index = 0; index < scene.skeletons.length; index++) {
  92105. var skeleton = scene.skeletons[index];
  92106. if (!skeleton.doNotSerialize) {
  92107. serializationObject.skeletons.push(skeleton.serialize());
  92108. }
  92109. }
  92110. // Transform nodes
  92111. serializationObject.transformNodes = [];
  92112. for (index = 0; index < scene.transformNodes.length; index++) {
  92113. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92114. }
  92115. // Geometries
  92116. serializationObject.geometries = {};
  92117. serializationObject.geometries.boxes = [];
  92118. serializationObject.geometries.spheres = [];
  92119. serializationObject.geometries.cylinders = [];
  92120. serializationObject.geometries.toruses = [];
  92121. serializationObject.geometries.grounds = [];
  92122. serializationObject.geometries.planes = [];
  92123. serializationObject.geometries.torusKnots = [];
  92124. serializationObject.geometries.vertexData = [];
  92125. serializedGeometries = [];
  92126. var geometries = scene.getGeometries();
  92127. for (index = 0; index < geometries.length; index++) {
  92128. var geometry = geometries[index];
  92129. if (geometry.isReady()) {
  92130. serializeGeometry(geometry, serializationObject.geometries);
  92131. }
  92132. }
  92133. // Meshes
  92134. serializationObject.meshes = [];
  92135. for (index = 0; index < scene.meshes.length; index++) {
  92136. var abstractMesh = scene.meshes[index];
  92137. if (abstractMesh instanceof BABYLON.Mesh) {
  92138. var mesh = abstractMesh;
  92139. if (!mesh.doNotSerialize) {
  92140. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92141. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92142. }
  92143. }
  92144. }
  92145. }
  92146. // Particles Systems
  92147. serializationObject.particleSystems = [];
  92148. for (index = 0; index < scene.particleSystems.length; index++) {
  92149. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92150. }
  92151. // Lens flares
  92152. serializationObject.lensFlareSystems = [];
  92153. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92154. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92155. }
  92156. // Shadows
  92157. serializationObject.shadowGenerators = [];
  92158. for (index = 0; index < scene.lights.length; index++) {
  92159. light = scene.lights[index];
  92160. var shadowGenerator = light.getShadowGenerator();
  92161. if (shadowGenerator) {
  92162. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92163. }
  92164. }
  92165. // Action Manager
  92166. if (scene.actionManager) {
  92167. serializationObject.actions = scene.actionManager.serialize("scene");
  92168. }
  92169. // Audio
  92170. serializationObject.sounds = [];
  92171. for (index = 0; index < scene.soundTracks.length; index++) {
  92172. var soundtrack = scene.soundTracks[index];
  92173. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  92174. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92175. }
  92176. }
  92177. // Effect layers
  92178. serializationObject.effectLayers = [];
  92179. for (index = 0; index < scene.effectLayers.length; index++) {
  92180. var layer = scene.effectLayers[index];
  92181. if (layer.serialize) {
  92182. serializationObject.effectLayers.push(layer.serialize());
  92183. }
  92184. }
  92185. return serializationObject;
  92186. };
  92187. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92188. if (withParents === void 0) { withParents = false; }
  92189. if (withChildren === void 0) { withChildren = false; }
  92190. var serializationObject = {};
  92191. SceneSerializer.ClearCache();
  92192. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92193. if (withParents || withChildren) {
  92194. //deliberate for loop! not for each, appended should be processed as well.
  92195. for (var i = 0; i < toSerialize.length; ++i) {
  92196. if (withChildren) {
  92197. toSerialize[i].getDescendants().forEach(function (node) {
  92198. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92199. toSerialize.push(node);
  92200. }
  92201. });
  92202. }
  92203. //make sure the array doesn't contain the object already
  92204. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92205. toSerialize.push(toSerialize[i].parent);
  92206. }
  92207. }
  92208. }
  92209. toSerialize.forEach(function (mesh) {
  92210. finalizeSingleMesh(mesh, serializationObject);
  92211. });
  92212. return serializationObject;
  92213. };
  92214. return SceneSerializer;
  92215. }());
  92216. BABYLON.SceneSerializer = SceneSerializer;
  92217. })(BABYLON || (BABYLON = {}));
  92218. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92219. var BABYLON;
  92220. (function (BABYLON) {
  92221. var ReflectionProbe = /** @class */ (function () {
  92222. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92223. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92224. var _this = this;
  92225. this.name = name;
  92226. this._viewMatrix = BABYLON.Matrix.Identity();
  92227. this._target = BABYLON.Vector3.Zero();
  92228. this._add = BABYLON.Vector3.Zero();
  92229. this._invertYAxis = false;
  92230. this.position = BABYLON.Vector3.Zero();
  92231. this._scene = scene;
  92232. this._scene.reflectionProbes.push(this);
  92233. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92234. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92235. switch (faceIndex) {
  92236. case 0:
  92237. _this._add.copyFromFloats(1, 0, 0);
  92238. break;
  92239. case 1:
  92240. _this._add.copyFromFloats(-1, 0, 0);
  92241. break;
  92242. case 2:
  92243. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92244. break;
  92245. case 3:
  92246. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92247. break;
  92248. case 4:
  92249. _this._add.copyFromFloats(0, 0, 1);
  92250. break;
  92251. case 5:
  92252. _this._add.copyFromFloats(0, 0, -1);
  92253. break;
  92254. }
  92255. if (_this._attachedMesh) {
  92256. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92257. }
  92258. _this.position.addToRef(_this._add, _this._target);
  92259. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92260. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92261. scene._forcedViewPosition = _this.position;
  92262. });
  92263. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92264. scene._forcedViewPosition = null;
  92265. scene.updateTransformMatrix(true);
  92266. });
  92267. if (scene.activeCamera) {
  92268. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92269. }
  92270. }
  92271. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92272. get: function () {
  92273. return this._renderTargetTexture.samples;
  92274. },
  92275. set: function (value) {
  92276. this._renderTargetTexture.samples = value;
  92277. },
  92278. enumerable: true,
  92279. configurable: true
  92280. });
  92281. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  92282. get: function () {
  92283. return this._renderTargetTexture.refreshRate;
  92284. },
  92285. set: function (value) {
  92286. this._renderTargetTexture.refreshRate = value;
  92287. },
  92288. enumerable: true,
  92289. configurable: true
  92290. });
  92291. ReflectionProbe.prototype.getScene = function () {
  92292. return this._scene;
  92293. };
  92294. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  92295. get: function () {
  92296. return this._renderTargetTexture;
  92297. },
  92298. enumerable: true,
  92299. configurable: true
  92300. });
  92301. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  92302. get: function () {
  92303. return this._renderTargetTexture.renderList;
  92304. },
  92305. enumerable: true,
  92306. configurable: true
  92307. });
  92308. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  92309. this._attachedMesh = mesh;
  92310. };
  92311. /**
  92312. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  92313. *
  92314. * @param renderingGroupId The rendering group id corresponding to its index
  92315. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  92316. */
  92317. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  92318. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  92319. };
  92320. ReflectionProbe.prototype.dispose = function () {
  92321. var index = this._scene.reflectionProbes.indexOf(this);
  92322. if (index !== -1) {
  92323. // Remove from the scene if found
  92324. this._scene.reflectionProbes.splice(index, 1);
  92325. }
  92326. if (this._renderTargetTexture) {
  92327. this._renderTargetTexture.dispose();
  92328. this._renderTargetTexture = null;
  92329. }
  92330. };
  92331. return ReflectionProbe;
  92332. }());
  92333. BABYLON.ReflectionProbe = ReflectionProbe;
  92334. })(BABYLON || (BABYLON = {}));
  92335. //# sourceMappingURL=babylon.reflectionProbe.js.map
  92336. var BABYLON;
  92337. (function (BABYLON) {
  92338. var Layer = /** @class */ (function () {
  92339. function Layer(name, imgUrl, scene, isBackground, color) {
  92340. this.name = name;
  92341. this.scale = new BABYLON.Vector2(1, 1);
  92342. this.offset = new BABYLON.Vector2(0, 0);
  92343. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  92344. this.layerMask = 0x0FFFFFFF;
  92345. this._vertexBuffers = {};
  92346. // Events
  92347. /**
  92348. * An event triggered when the layer is disposed.
  92349. */
  92350. this.onDisposeObservable = new BABYLON.Observable();
  92351. /**
  92352. * An event triggered before rendering the scene
  92353. */
  92354. this.onBeforeRenderObservable = new BABYLON.Observable();
  92355. /**
  92356. * An event triggered after rendering the scene
  92357. */
  92358. this.onAfterRenderObservable = new BABYLON.Observable();
  92359. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  92360. this.isBackground = isBackground === undefined ? true : isBackground;
  92361. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  92362. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  92363. this._scene.layers.push(this);
  92364. var engine = this._scene.getEngine();
  92365. // VBO
  92366. var vertices = [];
  92367. vertices.push(1, 1);
  92368. vertices.push(-1, 1);
  92369. vertices.push(-1, -1);
  92370. vertices.push(1, -1);
  92371. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92373. this._createIndexBuffer();
  92374. // Effects
  92375. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  92376. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  92377. }
  92378. Object.defineProperty(Layer.prototype, "onDispose", {
  92379. set: function (callback) {
  92380. if (this._onDisposeObserver) {
  92381. this.onDisposeObservable.remove(this._onDisposeObserver);
  92382. }
  92383. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  92384. },
  92385. enumerable: true,
  92386. configurable: true
  92387. });
  92388. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  92389. set: function (callback) {
  92390. if (this._onBeforeRenderObserver) {
  92391. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  92392. }
  92393. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  92394. },
  92395. enumerable: true,
  92396. configurable: true
  92397. });
  92398. Object.defineProperty(Layer.prototype, "onAfterRender", {
  92399. set: function (callback) {
  92400. if (this._onAfterRenderObserver) {
  92401. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  92402. }
  92403. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  92404. },
  92405. enumerable: true,
  92406. configurable: true
  92407. });
  92408. Layer.prototype._createIndexBuffer = function () {
  92409. var engine = this._scene.getEngine();
  92410. // Indices
  92411. var indices = [];
  92412. indices.push(0);
  92413. indices.push(1);
  92414. indices.push(2);
  92415. indices.push(0);
  92416. indices.push(2);
  92417. indices.push(3);
  92418. this._indexBuffer = engine.createIndexBuffer(indices);
  92419. };
  92420. Layer.prototype._rebuild = function () {
  92421. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92422. if (vb) {
  92423. vb._rebuild();
  92424. }
  92425. this._createIndexBuffer();
  92426. };
  92427. Layer.prototype.render = function () {
  92428. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  92429. // Check
  92430. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  92431. return;
  92432. var engine = this._scene.getEngine();
  92433. this.onBeforeRenderObservable.notifyObservers(this);
  92434. // Render
  92435. engine.enableEffect(currentEffect);
  92436. engine.setState(false);
  92437. // Texture
  92438. currentEffect.setTexture("textureSampler", this.texture);
  92439. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  92440. // Color
  92441. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  92442. // Scale / offset
  92443. currentEffect.setVector2("offset", this.offset);
  92444. currentEffect.setVector2("scale", this.scale);
  92445. // VBOs
  92446. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92447. // Draw order
  92448. if (!this.alphaTest) {
  92449. engine.setAlphaMode(this.alphaBlendingMode);
  92450. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92451. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92452. }
  92453. else {
  92454. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92455. }
  92456. this.onAfterRenderObservable.notifyObservers(this);
  92457. };
  92458. Layer.prototype.dispose = function () {
  92459. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92460. if (vertexBuffer) {
  92461. vertexBuffer.dispose();
  92462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92463. }
  92464. if (this._indexBuffer) {
  92465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92466. this._indexBuffer = null;
  92467. }
  92468. if (this.texture) {
  92469. this.texture.dispose();
  92470. this.texture = null;
  92471. }
  92472. // Remove from scene
  92473. var index = this._scene.layers.indexOf(this);
  92474. this._scene.layers.splice(index, 1);
  92475. // Callback
  92476. this.onDisposeObservable.notifyObservers(this);
  92477. this.onDisposeObservable.clear();
  92478. this.onAfterRenderObservable.clear();
  92479. this.onBeforeRenderObservable.clear();
  92480. };
  92481. return Layer;
  92482. }());
  92483. BABYLON.Layer = Layer;
  92484. })(BABYLON || (BABYLON = {}));
  92485. //# sourceMappingURL=babylon.layer.js.map
  92486. var BABYLON;
  92487. (function (BABYLON) {
  92488. var TextureTools = /** @class */ (function () {
  92489. function TextureTools() {
  92490. }
  92491. /**
  92492. * Uses the GPU to create a copy texture rescaled at a given size
  92493. * @param texture Texture to copy from
  92494. * @param width Desired width
  92495. * @param height Desired height
  92496. * @return Generated texture
  92497. */
  92498. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  92499. if (useBilinearMode === void 0) { useBilinearMode = true; }
  92500. var scene = texture.getScene();
  92501. var engine = scene.getEngine();
  92502. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  92503. rtt.wrapU = texture.wrapU;
  92504. rtt.wrapV = texture.wrapV;
  92505. rtt.uOffset = texture.uOffset;
  92506. rtt.vOffset = texture.vOffset;
  92507. rtt.uScale = texture.uScale;
  92508. rtt.vScale = texture.vScale;
  92509. rtt.uAng = texture.uAng;
  92510. rtt.vAng = texture.vAng;
  92511. rtt.wAng = texture.wAng;
  92512. rtt.coordinatesIndex = texture.coordinatesIndex;
  92513. rtt.level = texture.level;
  92514. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  92515. rtt._texture.isReady = false;
  92516. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92517. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92518. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92519. passPostProcess.getEffect().executeWhenCompiled(function () {
  92520. passPostProcess.onApply = function (effect) {
  92521. effect.setTexture("textureSampler", texture);
  92522. };
  92523. var internalTexture = rtt.getInternalTexture();
  92524. if (internalTexture) {
  92525. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  92526. engine.unBindFramebuffer(internalTexture);
  92527. rtt.disposeFramebufferObjects();
  92528. passPostProcess.dispose();
  92529. internalTexture.isReady = true;
  92530. }
  92531. });
  92532. return rtt;
  92533. };
  92534. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  92535. if (!scene._environmentBRDFTexture) {
  92536. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92537. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92538. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92539. scene._environmentBRDFTexture = texture;
  92540. }
  92541. return scene._environmentBRDFTexture;
  92542. };
  92543. 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=";
  92544. return TextureTools;
  92545. }());
  92546. BABYLON.TextureTools = TextureTools;
  92547. })(BABYLON || (BABYLON = {}));
  92548. //# sourceMappingURL=babylon.textureTools.js.map
  92549. var BABYLON;
  92550. (function (BABYLON) {
  92551. var FramingBehavior = /** @class */ (function () {
  92552. function FramingBehavior() {
  92553. this._mode = FramingBehavior.FitFrustumSidesMode;
  92554. this._radiusScale = 1.0;
  92555. this._positionScale = 0.5;
  92556. this._defaultElevation = 0.3;
  92557. this._elevationReturnTime = 1500;
  92558. this._elevationReturnWaitTime = 1000;
  92559. this._zoomStopsAnimation = false;
  92560. this._framingTime = 1500;
  92561. this._isPointerDown = false;
  92562. this._lastInteractionTime = -Infinity;
  92563. // Framing control
  92564. this._animatables = new Array();
  92565. this._betaIsAnimating = false;
  92566. }
  92567. Object.defineProperty(FramingBehavior.prototype, "name", {
  92568. get: function () {
  92569. return "Framing";
  92570. },
  92571. enumerable: true,
  92572. configurable: true
  92573. });
  92574. Object.defineProperty(FramingBehavior.prototype, "mode", {
  92575. /**
  92576. * Gets current mode used by the behavior.
  92577. */
  92578. get: function () {
  92579. return this._mode;
  92580. },
  92581. /**
  92582. * Sets the current mode used by the behavior
  92583. */
  92584. set: function (mode) {
  92585. this._mode = mode;
  92586. },
  92587. enumerable: true,
  92588. configurable: true
  92589. });
  92590. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92591. /**
  92592. * Gets the scale applied to the radius
  92593. */
  92594. get: function () {
  92595. return this._radiusScale;
  92596. },
  92597. /**
  92598. * Sets the scale applied to the radius (1 by default)
  92599. */
  92600. set: function (radius) {
  92601. this._radiusScale = radius;
  92602. },
  92603. enumerable: true,
  92604. configurable: true
  92605. });
  92606. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92607. /**
  92608. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92609. */
  92610. get: function () {
  92611. return this._positionScale;
  92612. },
  92613. /**
  92614. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92615. */
  92616. set: function (scale) {
  92617. this._positionScale = scale;
  92618. },
  92619. enumerable: true,
  92620. configurable: true
  92621. });
  92622. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92623. /**
  92624. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92625. * behaviour is triggered, in radians.
  92626. */
  92627. get: function () {
  92628. return this._defaultElevation;
  92629. },
  92630. /**
  92631. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92632. * behaviour is triggered, in radians.
  92633. */
  92634. set: function (elevation) {
  92635. this._defaultElevation = elevation;
  92636. },
  92637. enumerable: true,
  92638. configurable: true
  92639. });
  92640. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92641. /**
  92642. * Gets the time (in milliseconds) taken to return to the default beta position.
  92643. * Negative value indicates camera should not return to default.
  92644. */
  92645. get: function () {
  92646. return this._elevationReturnTime;
  92647. },
  92648. /**
  92649. * Sets the time (in milliseconds) taken to return to the default beta position.
  92650. * Negative value indicates camera should not return to default.
  92651. */
  92652. set: function (speed) {
  92653. this._elevationReturnTime = speed;
  92654. },
  92655. enumerable: true,
  92656. configurable: true
  92657. });
  92658. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92659. /**
  92660. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92661. */
  92662. get: function () {
  92663. return this._elevationReturnWaitTime;
  92664. },
  92665. /**
  92666. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92667. */
  92668. set: function (time) {
  92669. this._elevationReturnWaitTime = time;
  92670. },
  92671. enumerable: true,
  92672. configurable: true
  92673. });
  92674. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92675. /**
  92676. * Gets the flag that indicates if user zooming should stop animation.
  92677. */
  92678. get: function () {
  92679. return this._zoomStopsAnimation;
  92680. },
  92681. /**
  92682. * Sets the flag that indicates if user zooming should stop animation.
  92683. */
  92684. set: function (flag) {
  92685. this._zoomStopsAnimation = flag;
  92686. },
  92687. enumerable: true,
  92688. configurable: true
  92689. });
  92690. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92691. /**
  92692. * Gets the transition time when framing the mesh, in milliseconds
  92693. */
  92694. get: function () {
  92695. return this._framingTime;
  92696. },
  92697. /**
  92698. * Sets the transition time when framing the mesh, in milliseconds
  92699. */
  92700. set: function (time) {
  92701. this._framingTime = time;
  92702. },
  92703. enumerable: true,
  92704. configurable: true
  92705. });
  92706. FramingBehavior.prototype.init = function () {
  92707. // Do notihng
  92708. };
  92709. FramingBehavior.prototype.attach = function (camera) {
  92710. var _this = this;
  92711. this._attachedCamera = camera;
  92712. var scene = this._attachedCamera.getScene();
  92713. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92714. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92715. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92716. _this._isPointerDown = true;
  92717. return;
  92718. }
  92719. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92720. _this._isPointerDown = false;
  92721. }
  92722. });
  92723. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92724. if (mesh) {
  92725. _this.zoomOnMesh(mesh);
  92726. }
  92727. });
  92728. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92729. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92730. _this._applyUserInteraction();
  92731. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92732. // back to the default position after a given timeout
  92733. _this._maintainCameraAboveGround();
  92734. });
  92735. };
  92736. FramingBehavior.prototype.detach = function () {
  92737. if (!this._attachedCamera) {
  92738. return;
  92739. }
  92740. var scene = this._attachedCamera.getScene();
  92741. if (this._onPrePointerObservableObserver) {
  92742. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92743. }
  92744. if (this._onAfterCheckInputsObserver) {
  92745. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92746. }
  92747. if (this._onMeshTargetChangedObserver) {
  92748. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92749. }
  92750. this._attachedCamera = null;
  92751. };
  92752. /**
  92753. * Targets the given mesh and updates zoom level accordingly.
  92754. * @param mesh The mesh to target.
  92755. * @param radius Optional. If a cached radius position already exists, overrides default.
  92756. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92757. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92758. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92759. */
  92760. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92761. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92762. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92763. mesh.computeWorldMatrix(true);
  92764. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92765. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92766. };
  92767. /**
  92768. * Targets the given mesh with its children and updates zoom level accordingly.
  92769. * @param mesh The mesh to target.
  92770. * @param radius Optional. If a cached radius position already exists, overrides default.
  92771. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92772. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92773. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92774. */
  92775. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92776. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92777. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92778. mesh.computeWorldMatrix(true);
  92779. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92780. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92781. };
  92782. /**
  92783. * Targets the given meshes with their children and updates zoom level accordingly.
  92784. * @param meshes The mesh to target.
  92785. * @param radius Optional. If a cached radius position already exists, overrides default.
  92786. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92787. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92788. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92789. */
  92790. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92791. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92792. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92793. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92794. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92795. for (var i = 0; i < meshes.length; i++) {
  92796. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92797. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92798. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92799. }
  92800. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92801. };
  92802. /**
  92803. * Targets the given mesh and updates zoom level accordingly.
  92804. * @param mesh The mesh to target.
  92805. * @param radius Optional. If a cached radius position already exists, overrides default.
  92806. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92807. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92808. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92809. */
  92810. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92811. var _this = this;
  92812. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92813. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92814. var zoomTarget;
  92815. if (!this._attachedCamera) {
  92816. return;
  92817. }
  92818. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92819. var bottom = minimumWorld.y;
  92820. var top = maximumWorld.y;
  92821. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92822. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92823. if (focusOnOriginXZ) {
  92824. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92825. }
  92826. else {
  92827. var centerWorld = minimumWorld.add(radiusWorld);
  92828. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92829. }
  92830. if (!this._vectorTransition) {
  92831. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92832. }
  92833. this._betaIsAnimating = true;
  92834. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92835. if (animatable) {
  92836. this._animatables.push(animatable);
  92837. }
  92838. // sets the radius and lower radius bounds
  92839. // Small delta ensures camera is not always at lower zoom limit.
  92840. var radius = 0;
  92841. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92842. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92843. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92844. radius = position;
  92845. }
  92846. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92847. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92848. if (this._attachedCamera.lowerRadiusLimit === null) {
  92849. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92850. }
  92851. }
  92852. // Set sensibilities
  92853. var extend = maximumWorld.subtract(minimumWorld).length();
  92854. this._attachedCamera.panningSensibility = 5000 / extend;
  92855. this._attachedCamera.wheelPrecision = 100 / radius;
  92856. // transition to new radius
  92857. if (!this._radiusTransition) {
  92858. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92859. }
  92860. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92861. _this.stopAllAnimations();
  92862. if (onAnimationEnd) {
  92863. onAnimationEnd();
  92864. }
  92865. if (_this._attachedCamera) {
  92866. _this._attachedCamera.storeState();
  92867. }
  92868. });
  92869. if (animatable) {
  92870. this._animatables.push(animatable);
  92871. }
  92872. };
  92873. /**
  92874. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  92875. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  92876. * frustum width.
  92877. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  92878. * to fully enclose the mesh in the viewing frustum.
  92879. */
  92880. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  92881. var size = maximumWorld.subtract(minimumWorld);
  92882. var boxVectorGlobalDiagonal = size.length();
  92883. var frustumSlope = this._getFrustumSlope();
  92884. // Formula for setting distance
  92885. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  92886. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  92887. // Horizon distance
  92888. var radius = radiusWithoutFraming * this._radiusScale;
  92889. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  92890. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  92891. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  92892. var camera = this._attachedCamera;
  92893. if (!camera) {
  92894. return 0;
  92895. }
  92896. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92897. // Don't exceed the requested limit
  92898. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  92899. }
  92900. // Don't exceed the upper radius limit
  92901. if (camera.upperRadiusLimit) {
  92902. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  92903. }
  92904. return distance;
  92905. };
  92906. /**
  92907. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  92908. * is automatically returned to its default position (expected to be above ground plane).
  92909. */
  92910. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  92911. var _this = this;
  92912. if (this._elevationReturnTime < 0) {
  92913. return;
  92914. }
  92915. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  92916. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  92917. var limitBeta = Math.PI * 0.5;
  92918. // Bring the camera back up if below the ground plane
  92919. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  92920. this._betaIsAnimating = true;
  92921. //Transition to new position
  92922. this.stopAllAnimations();
  92923. if (!this._betaTransition) {
  92924. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92925. }
  92926. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  92927. _this._clearAnimationLocks();
  92928. _this.stopAllAnimations();
  92929. });
  92930. if (animatabe) {
  92931. this._animatables.push(animatabe);
  92932. }
  92933. }
  92934. };
  92935. /**
  92936. * Returns the frustum slope based on the canvas ratio and camera FOV
  92937. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  92938. */
  92939. FramingBehavior.prototype._getFrustumSlope = function () {
  92940. // Calculate the viewport ratio
  92941. // Aspect Ratio is Height/Width.
  92942. var camera = this._attachedCamera;
  92943. if (!camera) {
  92944. return BABYLON.Vector2.Zero();
  92945. }
  92946. var engine = camera.getScene().getEngine();
  92947. var aspectRatio = engine.getAspectRatio(camera);
  92948. // Camera FOV is the vertical field of view (top-bottom) in radians.
  92949. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  92950. var frustumSlopeY = Math.tan(camera.fov / 2);
  92951. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  92952. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  92953. // along the forward vector.
  92954. var frustumSlopeX = frustumSlopeY * aspectRatio;
  92955. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  92956. };
  92957. /**
  92958. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  92959. */
  92960. FramingBehavior.prototype._clearAnimationLocks = function () {
  92961. this._betaIsAnimating = false;
  92962. };
  92963. /**
  92964. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92965. */
  92966. FramingBehavior.prototype._applyUserInteraction = function () {
  92967. if (this.isUserIsMoving) {
  92968. this._lastInteractionTime = BABYLON.Tools.Now;
  92969. this.stopAllAnimations();
  92970. this._clearAnimationLocks();
  92971. }
  92972. };
  92973. /**
  92974. * Stops and removes all animations that have been applied to the camera
  92975. */
  92976. FramingBehavior.prototype.stopAllAnimations = function () {
  92977. if (this._attachedCamera) {
  92978. this._attachedCamera.animations = [];
  92979. }
  92980. while (this._animatables.length) {
  92981. if (this._animatables[0]) {
  92982. this._animatables[0].onAnimationEnd = null;
  92983. this._animatables[0].stop();
  92984. }
  92985. this._animatables.shift();
  92986. }
  92987. };
  92988. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  92989. /**
  92990. * Gets a value indicating if the user is moving the camera
  92991. */
  92992. get: function () {
  92993. if (!this._attachedCamera) {
  92994. return false;
  92995. }
  92996. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92997. this._attachedCamera.inertialBetaOffset !== 0 ||
  92998. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92999. this._attachedCamera.inertialPanningX !== 0 ||
  93000. this._attachedCamera.inertialPanningY !== 0 ||
  93001. this._isPointerDown;
  93002. },
  93003. enumerable: true,
  93004. configurable: true
  93005. });
  93006. /**
  93007. * The easing function used by animations
  93008. */
  93009. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93010. /**
  93011. * The easing mode used by animations
  93012. */
  93013. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93014. // Statics
  93015. /**
  93016. * The camera can move all the way towards the mesh.
  93017. */
  93018. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93019. /**
  93020. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93021. */
  93022. FramingBehavior.FitFrustumSidesMode = 1;
  93023. return FramingBehavior;
  93024. }());
  93025. BABYLON.FramingBehavior = FramingBehavior;
  93026. })(BABYLON || (BABYLON = {}));
  93027. //# sourceMappingURL=babylon.framingBehavior.js.map
  93028. var BABYLON;
  93029. (function (BABYLON) {
  93030. /**
  93031. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93032. */
  93033. var BouncingBehavior = /** @class */ (function () {
  93034. function BouncingBehavior() {
  93035. /**
  93036. * The duration of the animation, in milliseconds
  93037. */
  93038. this.transitionDuration = 450;
  93039. /**
  93040. * Length of the distance animated by the transition when lower radius is reached
  93041. */
  93042. this.lowerRadiusTransitionRange = 2;
  93043. /**
  93044. * Length of the distance animated by the transition when upper radius is reached
  93045. */
  93046. this.upperRadiusTransitionRange = -2;
  93047. this._autoTransitionRange = false;
  93048. // Animations
  93049. this._radiusIsAnimating = false;
  93050. this._radiusBounceTransition = null;
  93051. this._animatables = new Array();
  93052. }
  93053. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93054. get: function () {
  93055. return "Bouncing";
  93056. },
  93057. enumerable: true,
  93058. configurable: true
  93059. });
  93060. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93061. /**
  93062. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93063. */
  93064. get: function () {
  93065. return this._autoTransitionRange;
  93066. },
  93067. /**
  93068. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93069. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93070. */
  93071. set: function (value) {
  93072. var _this = this;
  93073. if (this._autoTransitionRange === value) {
  93074. return;
  93075. }
  93076. this._autoTransitionRange = value;
  93077. var camera = this._attachedCamera;
  93078. if (!camera) {
  93079. return;
  93080. }
  93081. if (value) {
  93082. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93083. if (!mesh) {
  93084. return;
  93085. }
  93086. mesh.computeWorldMatrix(true);
  93087. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93088. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93089. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93090. });
  93091. }
  93092. else if (this._onMeshTargetChangedObserver) {
  93093. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93094. }
  93095. },
  93096. enumerable: true,
  93097. configurable: true
  93098. });
  93099. BouncingBehavior.prototype.init = function () {
  93100. // Do notihng
  93101. };
  93102. BouncingBehavior.prototype.attach = function (camera) {
  93103. var _this = this;
  93104. this._attachedCamera = camera;
  93105. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93106. if (!_this._attachedCamera) {
  93107. return;
  93108. }
  93109. // Add the bounce animation to the lower radius limit
  93110. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93111. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93112. }
  93113. // Add the bounce animation to the upper radius limit
  93114. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93115. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93116. }
  93117. });
  93118. };
  93119. BouncingBehavior.prototype.detach = function () {
  93120. if (!this._attachedCamera) {
  93121. return;
  93122. }
  93123. if (this._onAfterCheckInputsObserver) {
  93124. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93125. }
  93126. if (this._onMeshTargetChangedObserver) {
  93127. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93128. }
  93129. this._attachedCamera = null;
  93130. };
  93131. /**
  93132. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93133. * @param radiusLimit The limit to check against.
  93134. * @return Bool to indicate if at limit.
  93135. */
  93136. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93137. if (!this._attachedCamera) {
  93138. return false;
  93139. }
  93140. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93141. return true;
  93142. }
  93143. return false;
  93144. };
  93145. /**
  93146. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93147. * @param radiusDelta The delta by which to animate to. Can be negative.
  93148. */
  93149. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93150. var _this = this;
  93151. if (!this._attachedCamera) {
  93152. return;
  93153. }
  93154. if (!this._radiusBounceTransition) {
  93155. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93156. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93157. }
  93158. // Prevent zoom until bounce has completed
  93159. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93160. this._attachedCamera.wheelPrecision = Infinity;
  93161. this._attachedCamera.inertialRadiusOffset = 0;
  93162. // Animate to the radius limit
  93163. this.stopAllAnimations();
  93164. this._radiusIsAnimating = true;
  93165. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93166. if (animatable) {
  93167. this._animatables.push(animatable);
  93168. }
  93169. };
  93170. /**
  93171. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93172. */
  93173. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93174. this._radiusIsAnimating = false;
  93175. if (this._attachedCamera) {
  93176. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93177. }
  93178. };
  93179. /**
  93180. * Stops and removes all animations that have been applied to the camera
  93181. */
  93182. BouncingBehavior.prototype.stopAllAnimations = function () {
  93183. if (this._attachedCamera) {
  93184. this._attachedCamera.animations = [];
  93185. }
  93186. while (this._animatables.length) {
  93187. this._animatables[0].onAnimationEnd = null;
  93188. this._animatables[0].stop();
  93189. this._animatables.shift();
  93190. }
  93191. };
  93192. /**
  93193. * The easing function used by animations
  93194. */
  93195. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93196. /**
  93197. * The easing mode used by animations
  93198. */
  93199. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93200. return BouncingBehavior;
  93201. }());
  93202. BABYLON.BouncingBehavior = BouncingBehavior;
  93203. })(BABYLON || (BABYLON = {}));
  93204. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93205. var BABYLON;
  93206. (function (BABYLON) {
  93207. var AutoRotationBehavior = /** @class */ (function () {
  93208. function AutoRotationBehavior() {
  93209. this._zoomStopsAnimation = false;
  93210. this._idleRotationSpeed = 0.05;
  93211. this._idleRotationWaitTime = 2000;
  93212. this._idleRotationSpinupTime = 2000;
  93213. this._isPointerDown = false;
  93214. this._lastFrameTime = null;
  93215. this._lastInteractionTime = -Infinity;
  93216. this._cameraRotationSpeed = 0;
  93217. this._lastFrameRadius = 0;
  93218. }
  93219. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93220. get: function () {
  93221. return "AutoRotation";
  93222. },
  93223. enumerable: true,
  93224. configurable: true
  93225. });
  93226. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93227. /**
  93228. * Gets the flag that indicates if user zooming should stop animation.
  93229. */
  93230. get: function () {
  93231. return this._zoomStopsAnimation;
  93232. },
  93233. /**
  93234. * Sets the flag that indicates if user zooming should stop animation.
  93235. */
  93236. set: function (flag) {
  93237. this._zoomStopsAnimation = flag;
  93238. },
  93239. enumerable: true,
  93240. configurable: true
  93241. });
  93242. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93243. /**
  93244. * Gets the default speed at which the camera rotates around the model.
  93245. */
  93246. get: function () {
  93247. return this._idleRotationSpeed;
  93248. },
  93249. /**
  93250. * Sets the default speed at which the camera rotates around the model.
  93251. */
  93252. set: function (speed) {
  93253. this._idleRotationSpeed = speed;
  93254. },
  93255. enumerable: true,
  93256. configurable: true
  93257. });
  93258. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93259. /**
  93260. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93261. */
  93262. get: function () {
  93263. return this._idleRotationWaitTime;
  93264. },
  93265. /**
  93266. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93267. */
  93268. set: function (time) {
  93269. this._idleRotationWaitTime = time;
  93270. },
  93271. enumerable: true,
  93272. configurable: true
  93273. });
  93274. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93275. /**
  93276. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93277. */
  93278. get: function () {
  93279. return this._idleRotationSpinupTime;
  93280. },
  93281. /**
  93282. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93283. */
  93284. set: function (time) {
  93285. this._idleRotationSpinupTime = time;
  93286. },
  93287. enumerable: true,
  93288. configurable: true
  93289. });
  93290. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  93291. /**
  93292. * Gets a value indicating if the camera is currently rotating because of this behavior
  93293. */
  93294. get: function () {
  93295. return Math.abs(this._cameraRotationSpeed) > 0;
  93296. },
  93297. enumerable: true,
  93298. configurable: true
  93299. });
  93300. AutoRotationBehavior.prototype.init = function () {
  93301. // Do notihng
  93302. };
  93303. AutoRotationBehavior.prototype.attach = function (camera) {
  93304. var _this = this;
  93305. this._attachedCamera = camera;
  93306. var scene = this._attachedCamera.getScene();
  93307. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93308. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93309. _this._isPointerDown = true;
  93310. return;
  93311. }
  93312. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93313. _this._isPointerDown = false;
  93314. }
  93315. });
  93316. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93317. var now = BABYLON.Tools.Now;
  93318. var dt = 0;
  93319. if (_this._lastFrameTime != null) {
  93320. dt = now - _this._lastFrameTime;
  93321. }
  93322. _this._lastFrameTime = now;
  93323. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93324. _this._applyUserInteraction();
  93325. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  93326. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  93327. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  93328. // Step camera rotation by rotation speed
  93329. if (_this._attachedCamera) {
  93330. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  93331. }
  93332. });
  93333. };
  93334. AutoRotationBehavior.prototype.detach = function () {
  93335. if (!this._attachedCamera) {
  93336. return;
  93337. }
  93338. var scene = this._attachedCamera.getScene();
  93339. if (this._onPrePointerObservableObserver) {
  93340. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93341. }
  93342. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93343. this._attachedCamera = null;
  93344. };
  93345. /**
  93346. * Returns true if user is scrolling.
  93347. * @return true if user is scrolling.
  93348. */
  93349. AutoRotationBehavior.prototype._userIsZooming = function () {
  93350. if (!this._attachedCamera) {
  93351. return false;
  93352. }
  93353. return this._attachedCamera.inertialRadiusOffset !== 0;
  93354. };
  93355. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  93356. if (!this._attachedCamera) {
  93357. return false;
  93358. }
  93359. var zoomHasHitLimit = false;
  93360. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  93361. zoomHasHitLimit = true;
  93362. }
  93363. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  93364. this._lastFrameRadius = this._attachedCamera.radius;
  93365. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  93366. };
  93367. /**
  93368. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93369. */
  93370. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  93371. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  93372. this._lastInteractionTime = BABYLON.Tools.Now;
  93373. }
  93374. };
  93375. // Tools
  93376. AutoRotationBehavior.prototype._userIsMoving = function () {
  93377. if (!this._attachedCamera) {
  93378. return false;
  93379. }
  93380. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93381. this._attachedCamera.inertialBetaOffset !== 0 ||
  93382. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93383. this._attachedCamera.inertialPanningX !== 0 ||
  93384. this._attachedCamera.inertialPanningY !== 0 ||
  93385. this._isPointerDown;
  93386. };
  93387. return AutoRotationBehavior;
  93388. }());
  93389. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  93390. })(BABYLON || (BABYLON = {}));
  93391. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  93392. var BABYLON;
  93393. (function (BABYLON) {
  93394. var NullEngineOptions = /** @class */ (function () {
  93395. function NullEngineOptions() {
  93396. this.renderWidth = 512;
  93397. this.renderHeight = 256;
  93398. this.textureSize = 512;
  93399. this.deterministicLockstep = false;
  93400. this.lockstepMaxSteps = 4;
  93401. }
  93402. return NullEngineOptions;
  93403. }());
  93404. BABYLON.NullEngineOptions = NullEngineOptions;
  93405. /**
  93406. * The null engine class provides support for headless version of babylon.js.
  93407. * This can be used in server side scenario or for testing purposes
  93408. */
  93409. var NullEngine = /** @class */ (function (_super) {
  93410. __extends(NullEngine, _super);
  93411. function NullEngine(options) {
  93412. if (options === void 0) { options = new NullEngineOptions(); }
  93413. var _this = _super.call(this, null) || this;
  93414. if (options.deterministicLockstep === undefined) {
  93415. options.deterministicLockstep = false;
  93416. }
  93417. if (options.lockstepMaxSteps === undefined) {
  93418. options.lockstepMaxSteps = 4;
  93419. }
  93420. _this._options = options;
  93421. // Init caps
  93422. // We consider we are on a webgl1 capable device
  93423. _this._caps = new BABYLON.EngineCapabilities();
  93424. _this._caps.maxTexturesImageUnits = 16;
  93425. _this._caps.maxVertexTextureImageUnits = 16;
  93426. _this._caps.maxTextureSize = 512;
  93427. _this._caps.maxCubemapTextureSize = 512;
  93428. _this._caps.maxRenderTextureSize = 512;
  93429. _this._caps.maxVertexAttribs = 16;
  93430. _this._caps.maxVaryingVectors = 16;
  93431. _this._caps.maxFragmentUniformVectors = 16;
  93432. _this._caps.maxVertexUniformVectors = 16;
  93433. // Extensions
  93434. _this._caps.standardDerivatives = false;
  93435. _this._caps.astc = null;
  93436. _this._caps.s3tc = null;
  93437. _this._caps.pvrtc = null;
  93438. _this._caps.etc1 = null;
  93439. _this._caps.etc2 = null;
  93440. _this._caps.textureAnisotropicFilterExtension = null;
  93441. _this._caps.maxAnisotropy = 0;
  93442. _this._caps.uintIndices = false;
  93443. _this._caps.fragmentDepthSupported = false;
  93444. _this._caps.highPrecisionShaderSupported = true;
  93445. _this._caps.colorBufferFloat = false;
  93446. _this._caps.textureFloat = false;
  93447. _this._caps.textureFloatLinearFiltering = false;
  93448. _this._caps.textureFloatRender = false;
  93449. _this._caps.textureHalfFloat = false;
  93450. _this._caps.textureHalfFloatLinearFiltering = false;
  93451. _this._caps.textureHalfFloatRender = false;
  93452. _this._caps.textureLOD = false;
  93453. _this._caps.drawBuffersExtension = false;
  93454. _this._caps.depthTextureExtension = false;
  93455. _this._caps.vertexArrayObject = false;
  93456. _this._caps.instancedArrays = false;
  93457. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  93458. // Wrappers
  93459. if (typeof URL === "undefined") {
  93460. URL = {
  93461. createObjectURL: function () { },
  93462. revokeObjectURL: function () { }
  93463. };
  93464. }
  93465. if (typeof Blob === "undefined") {
  93466. Blob = function () { };
  93467. }
  93468. return _this;
  93469. }
  93470. NullEngine.prototype.isDeterministicLockStep = function () {
  93471. return this._options.deterministicLockstep;
  93472. };
  93473. NullEngine.prototype.getLockstepMaxSteps = function () {
  93474. return this._options.lockstepMaxSteps;
  93475. };
  93476. NullEngine.prototype.getHardwareScalingLevel = function () {
  93477. return 1.0;
  93478. };
  93479. NullEngine.prototype.createVertexBuffer = function (vertices) {
  93480. return {
  93481. capacity: 0,
  93482. references: 1,
  93483. is32Bits: false
  93484. };
  93485. };
  93486. NullEngine.prototype.createIndexBuffer = function (indices) {
  93487. return {
  93488. capacity: 0,
  93489. references: 1,
  93490. is32Bits: false
  93491. };
  93492. };
  93493. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  93494. if (stencil === void 0) { stencil = false; }
  93495. };
  93496. NullEngine.prototype.getRenderWidth = function (useScreen) {
  93497. if (useScreen === void 0) { useScreen = false; }
  93498. if (!useScreen && this._currentRenderTarget) {
  93499. return this._currentRenderTarget.width;
  93500. }
  93501. return this._options.renderWidth;
  93502. };
  93503. NullEngine.prototype.getRenderHeight = function (useScreen) {
  93504. if (useScreen === void 0) { useScreen = false; }
  93505. if (!useScreen && this._currentRenderTarget) {
  93506. return this._currentRenderTarget.height;
  93507. }
  93508. return this._options.renderHeight;
  93509. };
  93510. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  93511. this._cachedViewport = viewport;
  93512. };
  93513. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  93514. return {
  93515. transformFeedback: null,
  93516. __SPECTOR_rebuildProgram: null
  93517. };
  93518. };
  93519. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  93520. return [];
  93521. };
  93522. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  93523. return [];
  93524. };
  93525. NullEngine.prototype.bindSamplers = function (effect) {
  93526. this._currentEffect = null;
  93527. };
  93528. NullEngine.prototype.enableEffect = function (effect) {
  93529. this._currentEffect = effect;
  93530. if (effect.onBind) {
  93531. effect.onBind(effect);
  93532. }
  93533. effect.onBindObservable.notifyObservers(effect);
  93534. };
  93535. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  93536. if (zOffset === void 0) { zOffset = 0; }
  93537. if (reverseSide === void 0) { reverseSide = false; }
  93538. };
  93539. NullEngine.prototype.setIntArray = function (uniform, array) {
  93540. };
  93541. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  93542. };
  93543. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  93544. };
  93545. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  93546. };
  93547. NullEngine.prototype.setFloatArray = function (uniform, array) {
  93548. };
  93549. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  93550. };
  93551. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  93552. };
  93553. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  93554. };
  93555. NullEngine.prototype.setArray = function (uniform, array) {
  93556. };
  93557. NullEngine.prototype.setArray2 = function (uniform, array) {
  93558. };
  93559. NullEngine.prototype.setArray3 = function (uniform, array) {
  93560. };
  93561. NullEngine.prototype.setArray4 = function (uniform, array) {
  93562. };
  93563. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  93564. };
  93565. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  93566. };
  93567. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  93568. };
  93569. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  93570. };
  93571. NullEngine.prototype.setFloat = function (uniform, value) {
  93572. };
  93573. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93574. };
  93575. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93576. };
  93577. NullEngine.prototype.setBool = function (uniform, bool) {
  93578. };
  93579. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93580. };
  93581. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93582. };
  93583. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93584. };
  93585. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93586. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93587. if (this._alphaMode === mode) {
  93588. return;
  93589. }
  93590. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93591. if (!noDepthWriteChange) {
  93592. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93593. }
  93594. this._alphaMode = mode;
  93595. };
  93596. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93597. };
  93598. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93599. if (this.preventCacheWipeBetweenFrames) {
  93600. return;
  93601. }
  93602. this.resetTextureCache();
  93603. this._currentEffect = null;
  93604. if (bruteForce) {
  93605. this._currentProgram = null;
  93606. this._stencilState.reset();
  93607. this._depthCullingState.reset();
  93608. this._alphaState.reset();
  93609. }
  93610. this._cachedVertexBuffers = null;
  93611. this._cachedIndexBuffer = null;
  93612. this._cachedEffectForVertexBuffers = null;
  93613. };
  93614. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93615. };
  93616. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93617. };
  93618. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93619. };
  93620. NullEngine.prototype._createTexture = function () {
  93621. return {};
  93622. };
  93623. NullEngine.prototype._releaseTexture = function (texture) {
  93624. };
  93625. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93627. if (onLoad === void 0) { onLoad = null; }
  93628. if (onError === void 0) { onError = null; }
  93629. if (buffer === void 0) { buffer = null; }
  93630. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93631. var url = String(urlArg);
  93632. texture.url = url;
  93633. texture.generateMipMaps = !noMipmap;
  93634. texture.samplingMode = samplingMode;
  93635. texture.invertY = invertY;
  93636. texture.baseWidth = this._options.textureSize;
  93637. texture.baseHeight = this._options.textureSize;
  93638. texture.width = this._options.textureSize;
  93639. texture.height = this._options.textureSize;
  93640. if (format) {
  93641. texture.format = format;
  93642. }
  93643. texture.isReady = true;
  93644. if (onLoad) {
  93645. onLoad();
  93646. }
  93647. return texture;
  93648. };
  93649. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93650. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93651. if (options !== undefined && typeof options === "object") {
  93652. fullOptions.generateMipMaps = options.generateMipMaps;
  93653. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93654. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93655. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93656. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93657. }
  93658. else {
  93659. fullOptions.generateMipMaps = options;
  93660. fullOptions.generateDepthBuffer = true;
  93661. fullOptions.generateStencilBuffer = false;
  93662. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93663. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93664. }
  93665. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93666. var width = size.width || size;
  93667. var height = size.height || size;
  93668. texture._depthStencilBuffer = {};
  93669. texture._framebuffer = {};
  93670. texture.baseWidth = width;
  93671. texture.baseHeight = height;
  93672. texture.width = width;
  93673. texture.height = height;
  93674. texture.isReady = true;
  93675. texture.samples = 1;
  93676. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93677. texture.samplingMode = fullOptions.samplingMode;
  93678. texture.type = fullOptions.type;
  93679. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93680. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93681. return texture;
  93682. };
  93683. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93684. texture.samplingMode = samplingMode;
  93685. };
  93686. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93687. if (this._currentRenderTarget) {
  93688. this.unBindFramebuffer(this._currentRenderTarget);
  93689. }
  93690. this._currentRenderTarget = texture;
  93691. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93692. if (this._cachedViewport && !forceFullscreenViewport) {
  93693. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93694. }
  93695. };
  93696. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93697. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93698. this._currentRenderTarget = null;
  93699. if (onBeforeUnbind) {
  93700. if (texture._MSAAFramebuffer) {
  93701. this._currentFramebuffer = texture._framebuffer;
  93702. }
  93703. onBeforeUnbind();
  93704. }
  93705. this._currentFramebuffer = null;
  93706. };
  93707. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93708. var vbo = {
  93709. capacity: 1,
  93710. references: 1,
  93711. is32Bits: false
  93712. };
  93713. return vbo;
  93714. };
  93715. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93716. if (offset === void 0) { offset = 0; }
  93717. };
  93718. /**
  93719. * Updates a dynamic vertex buffer.
  93720. * @param vertexBuffer the vertex buffer to update
  93721. * @param data the data used to update the vertex buffer
  93722. * @param byteOffset the byte offset of the data (optional)
  93723. * @param byteLength the byte length of the data (optional)
  93724. */
  93725. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93726. };
  93727. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93728. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93729. this._boundTexturesCache[this._activeChannel] = texture;
  93730. }
  93731. };
  93732. NullEngine.prototype._bindTexture = function (channel, texture) {
  93733. if (channel < 0) {
  93734. return;
  93735. }
  93736. this._bindTextureDirectly(0, texture);
  93737. };
  93738. NullEngine.prototype._releaseBuffer = function (buffer) {
  93739. buffer.references--;
  93740. if (buffer.references === 0) {
  93741. return true;
  93742. }
  93743. return false;
  93744. };
  93745. return NullEngine;
  93746. }(BABYLON.Engine));
  93747. BABYLON.NullEngine = NullEngine;
  93748. })(BABYLON || (BABYLON = {}));
  93749. //# sourceMappingURL=babylon.nullEngine.js.map
  93750. var BABYLON;
  93751. (function (BABYLON) {
  93752. /**
  93753. * This class can be used to get instrumentation data from a Babylon engine
  93754. */
  93755. var EngineInstrumentation = /** @class */ (function () {
  93756. function EngineInstrumentation(engine) {
  93757. this.engine = engine;
  93758. this._captureGPUFrameTime = false;
  93759. this._gpuFrameTime = new BABYLON.PerfCounter();
  93760. this._captureShaderCompilationTime = false;
  93761. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93762. // Observers
  93763. this._onBeginFrameObserver = null;
  93764. this._onEndFrameObserver = null;
  93765. this._onBeforeShaderCompilationObserver = null;
  93766. this._onAfterShaderCompilationObserver = null;
  93767. }
  93768. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93769. // Properties
  93770. /**
  93771. * Gets the perf counter used for GPU frame time
  93772. */
  93773. get: function () {
  93774. return this._gpuFrameTime;
  93775. },
  93776. enumerable: true,
  93777. configurable: true
  93778. });
  93779. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93780. /**
  93781. * Gets the GPU frame time capture status
  93782. */
  93783. get: function () {
  93784. return this._captureGPUFrameTime;
  93785. },
  93786. /**
  93787. * Enable or disable the GPU frame time capture
  93788. */
  93789. set: function (value) {
  93790. var _this = this;
  93791. if (value === this._captureGPUFrameTime) {
  93792. return;
  93793. }
  93794. this._captureGPUFrameTime = value;
  93795. if (value) {
  93796. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93797. if (!_this._gpuFrameTimeToken) {
  93798. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93799. }
  93800. });
  93801. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93802. if (!_this._gpuFrameTimeToken) {
  93803. return;
  93804. }
  93805. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93806. if (time > -1) {
  93807. _this._gpuFrameTimeToken = null;
  93808. _this._gpuFrameTime.fetchNewFrame();
  93809. _this._gpuFrameTime.addCount(time, true);
  93810. }
  93811. });
  93812. }
  93813. else {
  93814. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93815. this._onBeginFrameObserver = null;
  93816. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93817. this._onEndFrameObserver = null;
  93818. }
  93819. },
  93820. enumerable: true,
  93821. configurable: true
  93822. });
  93823. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93824. /**
  93825. * Gets the perf counter used for shader compilation time
  93826. */
  93827. get: function () {
  93828. return this._shaderCompilationTime;
  93829. },
  93830. enumerable: true,
  93831. configurable: true
  93832. });
  93833. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93834. /**
  93835. * Gets the shader compilation time capture status
  93836. */
  93837. get: function () {
  93838. return this._captureShaderCompilationTime;
  93839. },
  93840. /**
  93841. * Enable or disable the shader compilation time capture
  93842. */
  93843. set: function (value) {
  93844. var _this = this;
  93845. if (value === this._captureShaderCompilationTime) {
  93846. return;
  93847. }
  93848. this._captureShaderCompilationTime = value;
  93849. if (value) {
  93850. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93851. _this._shaderCompilationTime.fetchNewFrame();
  93852. _this._shaderCompilationTime.beginMonitoring();
  93853. });
  93854. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93855. _this._shaderCompilationTime.endMonitoring();
  93856. });
  93857. }
  93858. else {
  93859. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93860. this._onBeforeShaderCompilationObserver = null;
  93861. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93862. this._onAfterShaderCompilationObserver = null;
  93863. }
  93864. },
  93865. enumerable: true,
  93866. configurable: true
  93867. });
  93868. EngineInstrumentation.prototype.dispose = function () {
  93869. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93870. this._onBeginFrameObserver = null;
  93871. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93872. this._onEndFrameObserver = null;
  93873. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93874. this._onBeforeShaderCompilationObserver = null;
  93875. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93876. this._onAfterShaderCompilationObserver = null;
  93877. this.engine = null;
  93878. };
  93879. return EngineInstrumentation;
  93880. }());
  93881. BABYLON.EngineInstrumentation = EngineInstrumentation;
  93882. })(BABYLON || (BABYLON = {}));
  93883. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  93884. var BABYLON;
  93885. (function (BABYLON) {
  93886. /**
  93887. * This class can be used to get instrumentation data from a Babylon engine
  93888. */
  93889. var SceneInstrumentation = /** @class */ (function () {
  93890. function SceneInstrumentation(scene) {
  93891. var _this = this;
  93892. this.scene = scene;
  93893. this._captureActiveMeshesEvaluationTime = false;
  93894. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  93895. this._captureRenderTargetsRenderTime = false;
  93896. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  93897. this._captureFrameTime = false;
  93898. this._frameTime = new BABYLON.PerfCounter();
  93899. this._captureRenderTime = false;
  93900. this._renderTime = new BABYLON.PerfCounter();
  93901. this._captureInterFrameTime = false;
  93902. this._interFrameTime = new BABYLON.PerfCounter();
  93903. this._captureParticlesRenderTime = false;
  93904. this._particlesRenderTime = new BABYLON.PerfCounter();
  93905. this._captureSpritesRenderTime = false;
  93906. this._spritesRenderTime = new BABYLON.PerfCounter();
  93907. this._capturePhysicsTime = false;
  93908. this._physicsTime = new BABYLON.PerfCounter();
  93909. this._captureAnimationsTime = false;
  93910. this._animationsTime = new BABYLON.PerfCounter();
  93911. // Observers
  93912. this._onBeforeActiveMeshesEvaluationObserver = null;
  93913. this._onAfterActiveMeshesEvaluationObserver = null;
  93914. this._onBeforeRenderTargetsRenderObserver = null;
  93915. this._onAfterRenderTargetsRenderObserver = null;
  93916. this._onAfterRenderObserver = null;
  93917. this._onBeforeDrawPhaseObserver = null;
  93918. this._onAfterDrawPhaseObserver = null;
  93919. this._onBeforeAnimationsObserver = null;
  93920. this._onBeforeParticlesRenderingObserver = null;
  93921. this._onAfterParticlesRenderingObserver = null;
  93922. this._onBeforeSpritesRenderingObserver = null;
  93923. this._onAfterSpritesRenderingObserver = null;
  93924. this._onBeforePhysicsObserver = null;
  93925. this._onAfterPhysicsObserver = null;
  93926. this._onAfterAnimationsObserver = null;
  93927. // Before render
  93928. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  93929. if (_this._captureActiveMeshesEvaluationTime) {
  93930. _this._activeMeshesEvaluationTime.fetchNewFrame();
  93931. }
  93932. if (_this._captureRenderTargetsRenderTime) {
  93933. _this._renderTargetsRenderTime.fetchNewFrame();
  93934. }
  93935. if (_this._captureFrameTime) {
  93936. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  93937. _this._frameTime.beginMonitoring();
  93938. }
  93939. if (_this._captureInterFrameTime) {
  93940. _this._interFrameTime.endMonitoring();
  93941. }
  93942. if (_this._captureParticlesRenderTime) {
  93943. _this._particlesRenderTime.fetchNewFrame();
  93944. }
  93945. if (_this._captureSpritesRenderTime) {
  93946. _this._spritesRenderTime.fetchNewFrame();
  93947. }
  93948. if (_this._captureAnimationsTime) {
  93949. _this._animationsTime.beginMonitoring();
  93950. }
  93951. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  93952. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  93953. });
  93954. // After render
  93955. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  93956. if (_this._captureFrameTime) {
  93957. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  93958. _this._frameTime.endMonitoring();
  93959. }
  93960. if (_this._captureRenderTime) {
  93961. _this._renderTime.endMonitoring(false);
  93962. }
  93963. if (_this._captureInterFrameTime) {
  93964. _this._interFrameTime.beginMonitoring();
  93965. }
  93966. });
  93967. }
  93968. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  93969. // Properties
  93970. /**
  93971. * Gets the perf counter used for active meshes evaluation time
  93972. */
  93973. get: function () {
  93974. return this._activeMeshesEvaluationTime;
  93975. },
  93976. enumerable: true,
  93977. configurable: true
  93978. });
  93979. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  93980. /**
  93981. * Gets the active meshes evaluation time capture status
  93982. */
  93983. get: function () {
  93984. return this._captureActiveMeshesEvaluationTime;
  93985. },
  93986. /**
  93987. * Enable or disable the active meshes evaluation time capture
  93988. */
  93989. set: function (value) {
  93990. var _this = this;
  93991. if (value === this._captureActiveMeshesEvaluationTime) {
  93992. return;
  93993. }
  93994. this._captureActiveMeshesEvaluationTime = value;
  93995. if (value) {
  93996. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  93997. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  93998. _this._activeMeshesEvaluationTime.beginMonitoring();
  93999. });
  94000. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94001. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94002. _this._activeMeshesEvaluationTime.endMonitoring();
  94003. });
  94004. }
  94005. else {
  94006. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94007. this._onBeforeActiveMeshesEvaluationObserver = null;
  94008. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94009. this._onAfterActiveMeshesEvaluationObserver = null;
  94010. }
  94011. },
  94012. enumerable: true,
  94013. configurable: true
  94014. });
  94015. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94016. /**
  94017. * Gets the perf counter used for render targets render time
  94018. */
  94019. get: function () {
  94020. return this._renderTargetsRenderTime;
  94021. },
  94022. enumerable: true,
  94023. configurable: true
  94024. });
  94025. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94026. /**
  94027. * Gets the render targets render time capture status
  94028. */
  94029. get: function () {
  94030. return this._captureRenderTargetsRenderTime;
  94031. },
  94032. /**
  94033. * Enable or disable the render targets render time capture
  94034. */
  94035. set: function (value) {
  94036. var _this = this;
  94037. if (value === this._captureRenderTargetsRenderTime) {
  94038. return;
  94039. }
  94040. this._captureRenderTargetsRenderTime = value;
  94041. if (value) {
  94042. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94043. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94044. _this._renderTargetsRenderTime.beginMonitoring();
  94045. });
  94046. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94047. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94048. _this._renderTargetsRenderTime.endMonitoring(false);
  94049. });
  94050. }
  94051. else {
  94052. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94053. this._onBeforeRenderTargetsRenderObserver = null;
  94054. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94055. this._onAfterRenderTargetsRenderObserver = null;
  94056. }
  94057. },
  94058. enumerable: true,
  94059. configurable: true
  94060. });
  94061. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94062. /**
  94063. * Gets the perf counter used for particles render time
  94064. */
  94065. get: function () {
  94066. return this._particlesRenderTime;
  94067. },
  94068. enumerable: true,
  94069. configurable: true
  94070. });
  94071. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94072. /**
  94073. * Gets the particles render time capture status
  94074. */
  94075. get: function () {
  94076. return this._captureParticlesRenderTime;
  94077. },
  94078. /**
  94079. * Enable or disable the particles render time capture
  94080. */
  94081. set: function (value) {
  94082. var _this = this;
  94083. if (value === this._captureParticlesRenderTime) {
  94084. return;
  94085. }
  94086. this._captureParticlesRenderTime = value;
  94087. if (value) {
  94088. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94089. BABYLON.Tools.StartPerformanceCounter("Particles");
  94090. _this._particlesRenderTime.beginMonitoring();
  94091. });
  94092. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94093. BABYLON.Tools.EndPerformanceCounter("Particles");
  94094. _this._particlesRenderTime.endMonitoring(false);
  94095. });
  94096. }
  94097. else {
  94098. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94099. this._onBeforeParticlesRenderingObserver = null;
  94100. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94101. this._onAfterParticlesRenderingObserver = null;
  94102. }
  94103. },
  94104. enumerable: true,
  94105. configurable: true
  94106. });
  94107. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94108. /**
  94109. * Gets the perf counter used for sprites render time
  94110. */
  94111. get: function () {
  94112. return this._spritesRenderTime;
  94113. },
  94114. enumerable: true,
  94115. configurable: true
  94116. });
  94117. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94118. /**
  94119. * Gets the sprites render time capture status
  94120. */
  94121. get: function () {
  94122. return this._captureSpritesRenderTime;
  94123. },
  94124. /**
  94125. * Enable or disable the sprites render time capture
  94126. */
  94127. set: function (value) {
  94128. var _this = this;
  94129. if (value === this._captureSpritesRenderTime) {
  94130. return;
  94131. }
  94132. this._captureSpritesRenderTime = value;
  94133. if (value) {
  94134. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94135. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94136. _this._spritesRenderTime.beginMonitoring();
  94137. });
  94138. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94139. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94140. _this._spritesRenderTime.endMonitoring(false);
  94141. });
  94142. }
  94143. else {
  94144. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94145. this._onBeforeSpritesRenderingObserver = null;
  94146. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94147. this._onAfterSpritesRenderingObserver = null;
  94148. }
  94149. },
  94150. enumerable: true,
  94151. configurable: true
  94152. });
  94153. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94154. /**
  94155. * Gets the perf counter used for physics time
  94156. */
  94157. get: function () {
  94158. return this._physicsTime;
  94159. },
  94160. enumerable: true,
  94161. configurable: true
  94162. });
  94163. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94164. /**
  94165. * Gets the physics time capture status
  94166. */
  94167. get: function () {
  94168. return this._capturePhysicsTime;
  94169. },
  94170. /**
  94171. * Enable or disable the physics time capture
  94172. */
  94173. set: function (value) {
  94174. var _this = this;
  94175. if (value === this._capturePhysicsTime) {
  94176. return;
  94177. }
  94178. this._capturePhysicsTime = value;
  94179. if (value) {
  94180. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94181. BABYLON.Tools.StartPerformanceCounter("Physics");
  94182. _this._physicsTime.beginMonitoring();
  94183. });
  94184. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94185. BABYLON.Tools.EndPerformanceCounter("Physics");
  94186. _this._physicsTime.endMonitoring();
  94187. });
  94188. }
  94189. else {
  94190. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94191. this._onBeforePhysicsObserver = null;
  94192. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94193. this._onAfterPhysicsObserver = null;
  94194. }
  94195. },
  94196. enumerable: true,
  94197. configurable: true
  94198. });
  94199. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94200. /**
  94201. * Gets the perf counter used for animations time
  94202. */
  94203. get: function () {
  94204. return this._animationsTime;
  94205. },
  94206. enumerable: true,
  94207. configurable: true
  94208. });
  94209. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94210. /**
  94211. * Gets the animations time capture status
  94212. */
  94213. get: function () {
  94214. return this._captureAnimationsTime;
  94215. },
  94216. /**
  94217. * Enable or disable the animations time capture
  94218. */
  94219. set: function (value) {
  94220. var _this = this;
  94221. if (value === this._captureAnimationsTime) {
  94222. return;
  94223. }
  94224. this._captureAnimationsTime = value;
  94225. if (value) {
  94226. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94227. _this._animationsTime.endMonitoring();
  94228. });
  94229. }
  94230. else {
  94231. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94232. this._onAfterAnimationsObserver = null;
  94233. }
  94234. },
  94235. enumerable: true,
  94236. configurable: true
  94237. });
  94238. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94239. /**
  94240. * Gets the perf counter used for frame time capture
  94241. */
  94242. get: function () {
  94243. return this._frameTime;
  94244. },
  94245. enumerable: true,
  94246. configurable: true
  94247. });
  94248. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94249. /**
  94250. * Gets the frame time capture status
  94251. */
  94252. get: function () {
  94253. return this._captureFrameTime;
  94254. },
  94255. /**
  94256. * Enable or disable the frame time capture
  94257. */
  94258. set: function (value) {
  94259. this._captureFrameTime = value;
  94260. },
  94261. enumerable: true,
  94262. configurable: true
  94263. });
  94264. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94265. /**
  94266. * Gets the perf counter used for inter-frames time capture
  94267. */
  94268. get: function () {
  94269. return this._interFrameTime;
  94270. },
  94271. enumerable: true,
  94272. configurable: true
  94273. });
  94274. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94275. /**
  94276. * Gets the inter-frames time capture status
  94277. */
  94278. get: function () {
  94279. return this._captureInterFrameTime;
  94280. },
  94281. /**
  94282. * Enable or disable the inter-frames time capture
  94283. */
  94284. set: function (value) {
  94285. this._captureInterFrameTime = value;
  94286. },
  94287. enumerable: true,
  94288. configurable: true
  94289. });
  94290. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  94291. /**
  94292. * Gets the perf counter used for render time capture
  94293. */
  94294. get: function () {
  94295. return this._renderTime;
  94296. },
  94297. enumerable: true,
  94298. configurable: true
  94299. });
  94300. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  94301. /**
  94302. * Gets the render time capture status
  94303. */
  94304. get: function () {
  94305. return this._captureRenderTime;
  94306. },
  94307. /**
  94308. * Enable or disable the render time capture
  94309. */
  94310. set: function (value) {
  94311. var _this = this;
  94312. if (value === this._captureRenderTime) {
  94313. return;
  94314. }
  94315. this._captureRenderTime = value;
  94316. if (value) {
  94317. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  94318. _this._renderTime.beginMonitoring();
  94319. BABYLON.Tools.StartPerformanceCounter("Main render");
  94320. });
  94321. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  94322. _this._renderTime.endMonitoring(false);
  94323. BABYLON.Tools.EndPerformanceCounter("Main render");
  94324. });
  94325. }
  94326. else {
  94327. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94328. this._onBeforeDrawPhaseObserver = null;
  94329. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94330. this._onAfterDrawPhaseObserver = null;
  94331. }
  94332. },
  94333. enumerable: true,
  94334. configurable: true
  94335. });
  94336. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  94337. /**
  94338. * Gets the perf counter used for draw calls
  94339. */
  94340. get: function () {
  94341. return this.scene.getEngine()._drawCalls;
  94342. },
  94343. enumerable: true,
  94344. configurable: true
  94345. });
  94346. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  94347. /**
  94348. * Gets the perf counter used for texture collisions
  94349. */
  94350. get: function () {
  94351. return this.scene.getEngine()._textureCollisions;
  94352. },
  94353. enumerable: true,
  94354. configurable: true
  94355. });
  94356. SceneInstrumentation.prototype.dispose = function () {
  94357. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94358. this._onAfterRenderObserver = null;
  94359. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94360. this._onBeforeActiveMeshesEvaluationObserver = null;
  94361. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94362. this._onAfterActiveMeshesEvaluationObserver = null;
  94363. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94364. this._onBeforeRenderTargetsRenderObserver = null;
  94365. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94366. this._onAfterRenderTargetsRenderObserver = null;
  94367. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  94368. this._onBeforeAnimationsObserver = null;
  94369. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94370. this._onBeforeParticlesRenderingObserver = null;
  94371. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94372. this._onAfterParticlesRenderingObserver = null;
  94373. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94374. this._onBeforeSpritesRenderingObserver = null;
  94375. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94376. this._onAfterSpritesRenderingObserver = null;
  94377. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94378. this._onBeforeDrawPhaseObserver = null;
  94379. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94380. this._onAfterDrawPhaseObserver = null;
  94381. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94382. this._onBeforePhysicsObserver = null;
  94383. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94384. this._onAfterPhysicsObserver = null;
  94385. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94386. this._onAfterAnimationsObserver = null;
  94387. this.scene = null;
  94388. };
  94389. return SceneInstrumentation;
  94390. }());
  94391. BABYLON.SceneInstrumentation = SceneInstrumentation;
  94392. })(BABYLON || (BABYLON = {}));
  94393. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  94394. var BABYLON;
  94395. (function (BABYLON) {
  94396. var _TimeToken = /** @class */ (function () {
  94397. function _TimeToken() {
  94398. this._timeElapsedQueryEnded = false;
  94399. }
  94400. return _TimeToken;
  94401. }());
  94402. BABYLON._TimeToken = _TimeToken;
  94403. })(BABYLON || (BABYLON = {}));
  94404. //# sourceMappingURL=babylon.timeToken.js.map
  94405. var BABYLON;
  94406. (function (BABYLON) {
  94407. /**
  94408. * Background material defines definition.
  94409. * @ignore Mainly internal Use
  94410. */
  94411. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  94412. __extends(BackgroundMaterialDefines, _super);
  94413. /**
  94414. * Constructor of the defines.
  94415. */
  94416. function BackgroundMaterialDefines() {
  94417. var _this = _super.call(this) || this;
  94418. /**
  94419. * True if the diffuse texture is in use.
  94420. */
  94421. _this.DIFFUSE = false;
  94422. /**
  94423. * The direct UV channel to use.
  94424. */
  94425. _this.DIFFUSEDIRECTUV = 0;
  94426. /**
  94427. * True if the diffuse texture is in gamma space.
  94428. */
  94429. _this.GAMMADIFFUSE = false;
  94430. /**
  94431. * True if the diffuse texture has opacity in the alpha channel.
  94432. */
  94433. _this.DIFFUSEHASALPHA = false;
  94434. /**
  94435. * True if you want the material to fade to transparent at grazing angle.
  94436. */
  94437. _this.OPACITYFRESNEL = false;
  94438. /**
  94439. * True if an extra blur needs to be added in the reflection.
  94440. */
  94441. _this.REFLECTIONBLUR = false;
  94442. /**
  94443. * True if you want the material to fade to reflection at grazing angle.
  94444. */
  94445. _this.REFLECTIONFRESNEL = false;
  94446. /**
  94447. * True if you want the material to falloff as far as you move away from the scene center.
  94448. */
  94449. _this.REFLECTIONFALLOFF = false;
  94450. /**
  94451. * False if the current Webgl implementation does not support the texture lod extension.
  94452. */
  94453. _this.TEXTURELODSUPPORT = false;
  94454. /**
  94455. * True to ensure the data are premultiplied.
  94456. */
  94457. _this.PREMULTIPLYALPHA = false;
  94458. /**
  94459. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  94460. */
  94461. _this.USERGBCOLOR = false;
  94462. /**
  94463. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  94464. * stays aligned with the desired configuration.
  94465. */
  94466. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  94467. /**
  94468. * True to add noise in order to reduce the banding effect.
  94469. */
  94470. _this.NOISE = false;
  94471. /**
  94472. * is the reflection texture in BGR color scheme?
  94473. * Mainly used to solve a bug in ios10 video tag
  94474. */
  94475. _this.REFLECTIONBGR = false;
  94476. _this.IMAGEPROCESSING = false;
  94477. _this.VIGNETTE = false;
  94478. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  94479. _this.VIGNETTEBLENDMODEOPAQUE = false;
  94480. _this.TONEMAPPING = false;
  94481. _this.CONTRAST = false;
  94482. _this.COLORCURVES = false;
  94483. _this.COLORGRADING = false;
  94484. _this.COLORGRADING3D = false;
  94485. _this.SAMPLER3DGREENDEPTH = false;
  94486. _this.SAMPLER3DBGRMAP = false;
  94487. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  94488. _this.EXPOSURE = false;
  94489. // Reflection.
  94490. _this.REFLECTION = false;
  94491. _this.REFLECTIONMAP_3D = false;
  94492. _this.REFLECTIONMAP_SPHERICAL = false;
  94493. _this.REFLECTIONMAP_PLANAR = false;
  94494. _this.REFLECTIONMAP_CUBIC = false;
  94495. _this.REFLECTIONMAP_PROJECTION = false;
  94496. _this.REFLECTIONMAP_SKYBOX = false;
  94497. _this.REFLECTIONMAP_EXPLICIT = false;
  94498. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94499. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94500. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94501. _this.INVERTCUBICMAP = false;
  94502. _this.REFLECTIONMAP_OPPOSITEZ = false;
  94503. _this.LODINREFLECTIONALPHA = false;
  94504. _this.GAMMAREFLECTION = false;
  94505. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  94506. // Default BJS.
  94507. _this.MAINUV1 = false;
  94508. _this.MAINUV2 = false;
  94509. _this.UV1 = false;
  94510. _this.UV2 = false;
  94511. _this.CLIPPLANE = false;
  94512. _this.POINTSIZE = false;
  94513. _this.FOG = false;
  94514. _this.NORMAL = false;
  94515. _this.NUM_BONE_INFLUENCERS = 0;
  94516. _this.BonesPerMesh = 0;
  94517. _this.INSTANCES = false;
  94518. _this.SHADOWFLOAT = false;
  94519. _this.rebuild();
  94520. return _this;
  94521. }
  94522. return BackgroundMaterialDefines;
  94523. }(BABYLON.MaterialDefines));
  94524. /**
  94525. * Background material used to create an efficient environement around your scene.
  94526. */
  94527. var BackgroundMaterial = /** @class */ (function (_super) {
  94528. __extends(BackgroundMaterial, _super);
  94529. /**
  94530. * Instantiates a Background Material in the given scene
  94531. * @param name The friendly name of the material
  94532. * @param scene The scene to add the material to
  94533. */
  94534. function BackgroundMaterial(name, scene) {
  94535. var _this = _super.call(this, name, scene) || this;
  94536. /**
  94537. * Key light Color (multiply against the environement texture)
  94538. */
  94539. _this.primaryColor = BABYLON.Color3.White();
  94540. _this._primaryColorShadowLevel = 0;
  94541. _this._primaryColorHighlightLevel = 0;
  94542. /**
  94543. * Reflection Texture used in the material.
  94544. * Should be author in a specific way for the best result (refer to the documentation).
  94545. */
  94546. _this.reflectionTexture = null;
  94547. /**
  94548. * Reflection Texture level of blur.
  94549. *
  94550. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  94551. * texture twice.
  94552. */
  94553. _this.reflectionBlur = 0;
  94554. /**
  94555. * Diffuse Texture used in the material.
  94556. * Should be author in a specific way for the best result (refer to the documentation).
  94557. */
  94558. _this.diffuseTexture = null;
  94559. _this._shadowLights = null;
  94560. /**
  94561. * Specify the list of lights casting shadow on the material.
  94562. * All scene shadow lights will be included if null.
  94563. */
  94564. _this.shadowLights = null;
  94565. /**
  94566. * Helps adjusting the shadow to a softer level if required.
  94567. * 0 means black shadows and 1 means no shadows.
  94568. */
  94569. _this.shadowLevel = 0;
  94570. /**
  94571. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94572. * It is usually zero but might be interesting to modify according to your setup.
  94573. */
  94574. _this.sceneCenter = BABYLON.Vector3.Zero();
  94575. /**
  94576. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94577. * This helps ensuring a nice transition when the camera goes under the ground.
  94578. */
  94579. _this.opacityFresnel = true;
  94580. /**
  94581. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94582. * This helps adding a mirror texture on the ground.
  94583. */
  94584. _this.reflectionFresnel = false;
  94585. /**
  94586. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94587. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94588. */
  94589. _this.reflectionFalloffDistance = 0.0;
  94590. /**
  94591. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94592. */
  94593. _this.reflectionAmount = 1.0;
  94594. /**
  94595. * This specifies the weight of the reflection at grazing angle.
  94596. */
  94597. _this.reflectionReflectance0 = 0.05;
  94598. /**
  94599. * This specifies the weight of the reflection at a perpendicular point of view.
  94600. */
  94601. _this.reflectionReflectance90 = 0.5;
  94602. /**
  94603. * Helps to directly use the maps channels instead of their level.
  94604. */
  94605. _this.useRGBColor = true;
  94606. /**
  94607. * This helps reducing the banding effect that could occur on the background.
  94608. */
  94609. _this.enableNoise = false;
  94610. _this._fovMultiplier = 1.0;
  94611. /**
  94612. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94613. */
  94614. _this.useEquirectangularFOV = false;
  94615. _this._maxSimultaneousLights = 4;
  94616. /**
  94617. * Number of Simultaneous lights allowed on the material.
  94618. */
  94619. _this.maxSimultaneousLights = 4;
  94620. /**
  94621. * Keep track of the image processing observer to allow dispose and replace.
  94622. */
  94623. _this._imageProcessingObserver = null;
  94624. /**
  94625. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94626. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94627. */
  94628. _this.switchToBGR = false;
  94629. // Temp values kept as cache in the material.
  94630. _this._renderTargets = new BABYLON.SmartArray(16);
  94631. _this._reflectionControls = BABYLON.Vector4.Zero();
  94632. _this._white = BABYLON.Color3.White();
  94633. _this._primaryShadowColor = BABYLON.Color3.Black();
  94634. _this._primaryHighlightColor = BABYLON.Color3.Black();
  94635. // Setup the default processing configuration to the scene.
  94636. _this._attachImageProcessingConfiguration(null);
  94637. _this.getRenderTargetTextures = function () {
  94638. _this._renderTargets.reset();
  94639. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94640. _this._renderTargets.push(_this._diffuseTexture);
  94641. }
  94642. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94643. _this._renderTargets.push(_this._reflectionTexture);
  94644. }
  94645. return _this._renderTargets;
  94646. };
  94647. return _this;
  94648. }
  94649. Object.defineProperty(BackgroundMaterial.prototype, "perceptualColor", {
  94650. /**
  94651. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  94652. * This acts as a helper to set the primary color to a more "human friendly" value.
  94653. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  94654. * output color as close as possible from the chosen value.
  94655. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  94656. * part of lighting setup.)
  94657. */
  94658. get: function () {
  94659. return this._perceptualColor;
  94660. },
  94661. set: function (value) {
  94662. this._perceptualColor = value;
  94663. this._computePrimaryColorFromPerceptualColor();
  94664. this._markAllSubMeshesAsLightsDirty();
  94665. },
  94666. enumerable: true,
  94667. configurable: true
  94668. });
  94669. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  94670. /**
  94671. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  94672. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  94673. */
  94674. get: function () {
  94675. return this._primaryColorShadowLevel;
  94676. },
  94677. set: function (value) {
  94678. this._primaryColorShadowLevel = value;
  94679. this._computePrimaryColors();
  94680. this._markAllSubMeshesAsLightsDirty();
  94681. },
  94682. enumerable: true,
  94683. configurable: true
  94684. });
  94685. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  94686. /**
  94687. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  94688. * The primary color is used at the level chosen to define what the white area would look.
  94689. */
  94690. get: function () {
  94691. return this._primaryColorHighlightLevel;
  94692. },
  94693. set: function (value) {
  94694. this._primaryColorHighlightLevel = value;
  94695. this._computePrimaryColors();
  94696. this._markAllSubMeshesAsLightsDirty();
  94697. },
  94698. enumerable: true,
  94699. configurable: true
  94700. });
  94701. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94702. /**
  94703. * Sets the reflection reflectance fresnel values according to the default standard
  94704. * empirically know to work well :-)
  94705. */
  94706. set: function (value) {
  94707. var reflectionWeight = value;
  94708. if (reflectionWeight < 0.5) {
  94709. reflectionWeight = reflectionWeight * 2.0;
  94710. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94711. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94712. }
  94713. else {
  94714. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94715. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94716. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94717. }
  94718. },
  94719. enumerable: true,
  94720. configurable: true
  94721. });
  94722. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94723. /**
  94724. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94725. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94726. * Recommended to be keep at 1.0 except for special cases.
  94727. */
  94728. get: function () {
  94729. return this._fovMultiplier;
  94730. },
  94731. set: function (value) {
  94732. if (isNaN(value)) {
  94733. value = 1.0;
  94734. }
  94735. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94736. },
  94737. enumerable: true,
  94738. configurable: true
  94739. });
  94740. /**
  94741. * Attaches a new image processing configuration to the PBR Material.
  94742. * @param configuration (if null the scene configuration will be use)
  94743. */
  94744. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94745. var _this = this;
  94746. if (configuration === this._imageProcessingConfiguration) {
  94747. return;
  94748. }
  94749. // Detaches observer.
  94750. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94751. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94752. }
  94753. // Pick the scene configuration if needed.
  94754. if (!configuration) {
  94755. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94756. }
  94757. else {
  94758. this._imageProcessingConfiguration = configuration;
  94759. }
  94760. // Attaches observer.
  94761. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94762. _this._computePrimaryColorFromPerceptualColor();
  94763. _this._markAllSubMeshesAsImageProcessingDirty();
  94764. });
  94765. };
  94766. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94767. /**
  94768. * Gets the image processing configuration used either in this material.
  94769. */
  94770. get: function () {
  94771. return this._imageProcessingConfiguration;
  94772. },
  94773. /**
  94774. * Sets the Default image processing configuration used either in the this material.
  94775. *
  94776. * If sets to null, the scene one is in use.
  94777. */
  94778. set: function (value) {
  94779. this._attachImageProcessingConfiguration(value);
  94780. // Ensure the effect will be rebuilt.
  94781. this._markAllSubMeshesAsTexturesDirty();
  94782. },
  94783. enumerable: true,
  94784. configurable: true
  94785. });
  94786. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94787. /**
  94788. * Gets wether the color curves effect is enabled.
  94789. */
  94790. get: function () {
  94791. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94792. },
  94793. /**
  94794. * Sets wether the color curves effect is enabled.
  94795. */
  94796. set: function (value) {
  94797. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94798. },
  94799. enumerable: true,
  94800. configurable: true
  94801. });
  94802. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94803. /**
  94804. * Gets wether the color grading effect is enabled.
  94805. */
  94806. get: function () {
  94807. return this.imageProcessingConfiguration.colorGradingEnabled;
  94808. },
  94809. /**
  94810. * Gets wether the color grading effect is enabled.
  94811. */
  94812. set: function (value) {
  94813. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94814. },
  94815. enumerable: true,
  94816. configurable: true
  94817. });
  94818. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94819. /**
  94820. * Gets wether tonemapping is enabled or not.
  94821. */
  94822. get: function () {
  94823. return this._imageProcessingConfiguration.toneMappingEnabled;
  94824. },
  94825. /**
  94826. * Sets wether tonemapping is enabled or not
  94827. */
  94828. set: function (value) {
  94829. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94830. },
  94831. enumerable: true,
  94832. configurable: true
  94833. });
  94834. ;
  94835. ;
  94836. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94837. /**
  94838. * The camera exposure used on this material.
  94839. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94840. * This corresponds to a photographic exposure.
  94841. */
  94842. get: function () {
  94843. return this._imageProcessingConfiguration.exposure;
  94844. },
  94845. /**
  94846. * The camera exposure used on this material.
  94847. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94848. * This corresponds to a photographic exposure.
  94849. */
  94850. set: function (value) {
  94851. this._imageProcessingConfiguration.exposure = value;
  94852. },
  94853. enumerable: true,
  94854. configurable: true
  94855. });
  94856. ;
  94857. ;
  94858. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94859. /**
  94860. * Gets The camera contrast used on this material.
  94861. */
  94862. get: function () {
  94863. return this._imageProcessingConfiguration.contrast;
  94864. },
  94865. /**
  94866. * Sets The camera contrast used on this material.
  94867. */
  94868. set: function (value) {
  94869. this._imageProcessingConfiguration.contrast = value;
  94870. },
  94871. enumerable: true,
  94872. configurable: true
  94873. });
  94874. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  94875. /**
  94876. * Gets the Color Grading 2D Lookup Texture.
  94877. */
  94878. get: function () {
  94879. return this._imageProcessingConfiguration.colorGradingTexture;
  94880. },
  94881. /**
  94882. * Sets the Color Grading 2D Lookup Texture.
  94883. */
  94884. set: function (value) {
  94885. this.imageProcessingConfiguration.colorGradingTexture = value;
  94886. },
  94887. enumerable: true,
  94888. configurable: true
  94889. });
  94890. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  94891. /**
  94892. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94893. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94894. * 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;
  94895. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94896. */
  94897. get: function () {
  94898. return this.imageProcessingConfiguration.colorCurves;
  94899. },
  94900. /**
  94901. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94902. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94903. * 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;
  94904. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94905. */
  94906. set: function (value) {
  94907. this.imageProcessingConfiguration.colorCurves = value;
  94908. },
  94909. enumerable: true,
  94910. configurable: true
  94911. });
  94912. /**
  94913. * The entire material has been created in order to prevent overdraw.
  94914. * @returns false
  94915. */
  94916. BackgroundMaterial.prototype.needAlphaTesting = function () {
  94917. return true;
  94918. };
  94919. /**
  94920. * The entire material has been created in order to prevent overdraw.
  94921. * @returns true if blending is enable
  94922. */
  94923. BackgroundMaterial.prototype.needAlphaBlending = function () {
  94924. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  94925. };
  94926. /**
  94927. * Checks wether the material is ready to be rendered for a given mesh.
  94928. * @param mesh The mesh to render
  94929. * @param subMesh The submesh to check against
  94930. * @param useInstances Specify wether or not the material is used with instances
  94931. * @returns true if all the dependencies are ready (Textures, Effects...)
  94932. */
  94933. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  94934. var _this = this;
  94935. if (useInstances === void 0) { useInstances = false; }
  94936. if (subMesh.effect && this.isFrozen) {
  94937. if (this._wasPreviouslyReady) {
  94938. return true;
  94939. }
  94940. }
  94941. if (!subMesh._materialDefines) {
  94942. subMesh._materialDefines = new BackgroundMaterialDefines();
  94943. }
  94944. var scene = this.getScene();
  94945. var defines = subMesh._materialDefines;
  94946. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  94947. if (defines._renderId === scene.getRenderId()) {
  94948. return true;
  94949. }
  94950. }
  94951. var engine = scene.getEngine();
  94952. // Lights
  94953. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  94954. defines._needNormals = true;
  94955. // Textures
  94956. if (defines._areTexturesDirty) {
  94957. defines._needUVs = false;
  94958. if (scene.texturesEnabled) {
  94959. if (scene.getEngine().getCaps().textureLOD) {
  94960. defines.TEXTURELODSUPPORT = true;
  94961. }
  94962. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94963. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  94964. return false;
  94965. }
  94966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  94967. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  94968. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  94969. defines.OPACITYFRESNEL = this._opacityFresnel;
  94970. }
  94971. else {
  94972. defines.DIFFUSE = false;
  94973. defines.DIFFUSEHASALPHA = false;
  94974. defines.GAMMADIFFUSE = false;
  94975. defines.OPACITYFRESNEL = false;
  94976. }
  94977. var reflectionTexture = this._reflectionTexture;
  94978. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94979. if (!reflectionTexture.isReadyOrNotBlocking()) {
  94980. return false;
  94981. }
  94982. defines.REFLECTION = true;
  94983. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  94984. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  94985. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  94986. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  94987. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  94988. defines.REFLECTIONBGR = this.switchToBGR;
  94989. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  94990. defines.INVERTCUBICMAP = true;
  94991. }
  94992. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  94993. switch (reflectionTexture.coordinatesMode) {
  94994. case BABYLON.Texture.CUBIC_MODE:
  94995. case BABYLON.Texture.INVCUBIC_MODE:
  94996. defines.REFLECTIONMAP_CUBIC = true;
  94997. break;
  94998. case BABYLON.Texture.EXPLICIT_MODE:
  94999. defines.REFLECTIONMAP_EXPLICIT = true;
  95000. break;
  95001. case BABYLON.Texture.PLANAR_MODE:
  95002. defines.REFLECTIONMAP_PLANAR = true;
  95003. break;
  95004. case BABYLON.Texture.PROJECTION_MODE:
  95005. defines.REFLECTIONMAP_PROJECTION = true;
  95006. break;
  95007. case BABYLON.Texture.SKYBOX_MODE:
  95008. defines.REFLECTIONMAP_SKYBOX = true;
  95009. break;
  95010. case BABYLON.Texture.SPHERICAL_MODE:
  95011. defines.REFLECTIONMAP_SPHERICAL = true;
  95012. break;
  95013. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95014. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95015. break;
  95016. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95017. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95018. break;
  95019. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95020. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95021. break;
  95022. }
  95023. if (this.reflectionFresnel) {
  95024. defines.REFLECTIONFRESNEL = true;
  95025. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95026. this._reflectionControls.x = this.reflectionAmount;
  95027. this._reflectionControls.y = this.reflectionReflectance0;
  95028. this._reflectionControls.z = this.reflectionReflectance90;
  95029. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95030. }
  95031. else {
  95032. defines.REFLECTIONFRESNEL = false;
  95033. defines.REFLECTIONFALLOFF = false;
  95034. }
  95035. }
  95036. else {
  95037. defines.REFLECTION = false;
  95038. defines.REFLECTIONFALLOFF = false;
  95039. defines.REFLECTIONBLUR = false;
  95040. defines.REFLECTIONMAP_3D = false;
  95041. defines.REFLECTIONMAP_SPHERICAL = false;
  95042. defines.REFLECTIONMAP_PLANAR = false;
  95043. defines.REFLECTIONMAP_CUBIC = false;
  95044. defines.REFLECTIONMAP_PROJECTION = false;
  95045. defines.REFLECTIONMAP_SKYBOX = false;
  95046. defines.REFLECTIONMAP_EXPLICIT = false;
  95047. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95048. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95049. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95050. defines.INVERTCUBICMAP = false;
  95051. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95052. defines.LODINREFLECTIONALPHA = false;
  95053. defines.GAMMAREFLECTION = false;
  95054. }
  95055. }
  95056. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95057. defines.USERGBCOLOR = this._useRGBColor;
  95058. defines.NOISE = this._enableNoise;
  95059. }
  95060. if (defines._areLightsDirty) {
  95061. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95062. }
  95063. if (defines._areImageProcessingDirty) {
  95064. if (!this._imageProcessingConfiguration.isReady()) {
  95065. return false;
  95066. }
  95067. this._imageProcessingConfiguration.prepareDefines(defines);
  95068. }
  95069. // Misc.
  95070. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95071. // Values that need to be evaluated on every frame
  95072. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95073. // Attribs
  95074. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95075. if (mesh) {
  95076. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95077. mesh.createNormals(true);
  95078. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95079. }
  95080. }
  95081. }
  95082. // Get correct effect
  95083. if (defines.isDirty) {
  95084. defines.markAsProcessed();
  95085. scene.resetCachedMaterial();
  95086. // Fallbacks
  95087. var fallbacks = new BABYLON.EffectFallbacks();
  95088. if (defines.FOG) {
  95089. fallbacks.addFallback(0, "FOG");
  95090. }
  95091. if (defines.POINTSIZE) {
  95092. fallbacks.addFallback(1, "POINTSIZE");
  95093. }
  95094. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95095. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95096. fallbacks.addCPUSkinningFallback(0, mesh);
  95097. }
  95098. //Attributes
  95099. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95100. if (defines.NORMAL) {
  95101. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95102. }
  95103. if (defines.UV1) {
  95104. attribs.push(BABYLON.VertexBuffer.UVKind);
  95105. }
  95106. if (defines.UV2) {
  95107. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95108. }
  95109. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95110. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95111. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95112. "vFogInfos", "vFogColor", "pointSize",
  95113. "vClipPlane", "mBones",
  95114. "vPrimaryColor", "vPrimaryColorShadow",
  95115. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95116. "shadowLevel", "alpha",
  95117. "vBackgroundCenter", "vReflectionControl",
  95118. "vDiffuseInfos", "diffuseMatrix",
  95119. ];
  95120. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95121. var uniformBuffers = ["Material", "Scene"];
  95122. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95123. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95124. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95125. uniformsNames: uniforms,
  95126. uniformBuffersNames: uniformBuffers,
  95127. samplers: samplers,
  95128. defines: defines,
  95129. maxSimultaneousLights: this._maxSimultaneousLights
  95130. });
  95131. var onCompiled = function (effect) {
  95132. if (_this.onCompiled) {
  95133. _this.onCompiled(effect);
  95134. }
  95135. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95136. };
  95137. var join = defines.toString();
  95138. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95139. attributes: attribs,
  95140. uniformsNames: uniforms,
  95141. uniformBuffersNames: uniformBuffers,
  95142. samplers: samplers,
  95143. defines: join,
  95144. fallbacks: fallbacks,
  95145. onCompiled: onCompiled,
  95146. onError: this.onError,
  95147. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95148. }, engine), defines);
  95149. this.buildUniformLayout();
  95150. }
  95151. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95152. return false;
  95153. }
  95154. defines._renderId = scene.getRenderId();
  95155. this._wasPreviouslyReady = true;
  95156. return true;
  95157. };
  95158. /**
  95159. * Compute the primary color according to the chosen perceptual color.
  95160. */
  95161. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  95162. if (!this._perceptualColor) {
  95163. return;
  95164. }
  95165. this._primaryColor.copyFrom(this._perceptualColor);
  95166. // Revert gamma space.
  95167. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  95168. // Revert image processing configuration.
  95169. if (this._imageProcessingConfiguration) {
  95170. // Revert tone mapping.
  95171. if (this._imageProcessingConfiguration.toneMappingEnabled) {
  95172. // shader reference.
  95173. // tonemapped.rgb = 1.0 - exp2(-tonemappingCalibration * color.rgb);
  95174. // providing
  95175. // log2(1.0 - tonemapped.rgb) / -tonemappingCalibration = color.rgb;
  95176. // 1.0 - tonemapped.rgb
  95177. this._white.subtractToRef(this._primaryColor, this._primaryColor);
  95178. // log2(1.0 - tonemapped.rgb)
  95179. this._primaryColor.r = BABYLON.Scalar.Log2(this._primaryColor.r);
  95180. this._primaryColor.g = BABYLON.Scalar.Log2(this._primaryColor.g);
  95181. this._primaryColor.b = BABYLON.Scalar.Log2(this._primaryColor.b);
  95182. // log2(1.0 - tonemapped.rgb) / -tonemappingCalibration
  95183. this._primaryColor.scaleToRef(-1 / BackgroundMaterial._tonemappingCalibration, this._primaryColor);
  95184. }
  95185. // Revert Exposure.
  95186. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  95187. }
  95188. this._computePrimaryColors();
  95189. };
  95190. /**
  95191. * Compute the highlights and shadow colors according to their chosen levels.
  95192. */
  95193. BackgroundMaterial.prototype._computePrimaryColors = function () {
  95194. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  95195. return;
  95196. }
  95197. // Find the highlight color based on the configuration.
  95198. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  95199. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  95200. this._primaryShadowColor.clampToRef(0, 1, this._primaryShadowColor);
  95201. // Find the shadow color based on the configuration.
  95202. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  95203. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  95204. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  95205. this._primaryHighlightColor.clampToRef(0, 1, this._primaryHighlightColor);
  95206. };
  95207. /**
  95208. * Build the uniform buffer used in the material.
  95209. */
  95210. BackgroundMaterial.prototype.buildUniformLayout = function () {
  95211. // Order is important !
  95212. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  95213. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  95214. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  95215. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  95216. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  95217. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  95218. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  95219. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  95220. this._uniformBuffer.addUniform("pointSize", 1);
  95221. this._uniformBuffer.addUniform("shadowLevel", 1);
  95222. this._uniformBuffer.addUniform("alpha", 1);
  95223. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  95224. this._uniformBuffer.addUniform("vReflectionControl", 4);
  95225. this._uniformBuffer.create();
  95226. };
  95227. /**
  95228. * Unbind the material.
  95229. */
  95230. BackgroundMaterial.prototype.unbind = function () {
  95231. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  95232. this._uniformBuffer.setTexture("diffuseSampler", null);
  95233. }
  95234. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  95235. this._uniformBuffer.setTexture("reflectionSampler", null);
  95236. }
  95237. _super.prototype.unbind.call(this);
  95238. };
  95239. /**
  95240. * Bind only the world matrix to the material.
  95241. * @param world The world matrix to bind.
  95242. */
  95243. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  95244. this._activeEffect.setMatrix("world", world);
  95245. };
  95246. /**
  95247. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  95248. * @param world The world matrix to bind.
  95249. * @param subMesh The submesh to bind for.
  95250. */
  95251. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  95252. var scene = this.getScene();
  95253. var defines = subMesh._materialDefines;
  95254. if (!defines) {
  95255. return;
  95256. }
  95257. var effect = subMesh.effect;
  95258. if (!effect) {
  95259. return;
  95260. }
  95261. this._activeEffect = effect;
  95262. // Matrices
  95263. this.bindOnlyWorldMatrix(world);
  95264. // Bones
  95265. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95266. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95267. if (mustRebind) {
  95268. this._uniformBuffer.bindToEffect(effect, "Material");
  95269. this.bindViewProjection(effect);
  95270. var reflectionTexture = this._reflectionTexture;
  95271. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95272. // Texture uniforms
  95273. if (scene.texturesEnabled) {
  95274. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95275. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95276. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95277. }
  95278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95279. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95280. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95281. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95282. }
  95283. }
  95284. if (this.shadowLevel > 0) {
  95285. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95286. }
  95287. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95288. // Point size
  95289. if (this.pointsCloud) {
  95290. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95291. }
  95292. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  95293. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  95294. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  95295. }
  95296. else {
  95297. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  95298. }
  95299. }
  95300. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  95301. // Textures
  95302. if (scene.texturesEnabled) {
  95303. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95304. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  95305. }
  95306. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95307. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  95308. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95309. }
  95310. else if (!defines.REFLECTIONBLUR) {
  95311. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95312. }
  95313. else {
  95314. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  95315. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  95316. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  95317. }
  95318. if (defines.REFLECTIONFRESNEL) {
  95319. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  95320. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  95321. }
  95322. }
  95323. }
  95324. // Clip plane
  95325. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  95326. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  95327. }
  95328. if (mustRebind || !this.isFrozen) {
  95329. if (scene.lightsEnabled) {
  95330. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  95331. }
  95332. // View
  95333. this.bindView(effect);
  95334. // Fog
  95335. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  95336. // image processing
  95337. this._imageProcessingConfiguration.bind(this._activeEffect);
  95338. }
  95339. this._uniformBuffer.update();
  95340. this._afterBind(mesh);
  95341. };
  95342. /**
  95343. * Dispose the material.
  95344. * @param forceDisposeEffect Force disposal of the associated effect.
  95345. * @param forceDisposeTextures Force disposal of the associated textures.
  95346. */
  95347. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  95348. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  95349. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  95350. if (forceDisposeTextures) {
  95351. if (this.diffuseTexture) {
  95352. this.diffuseTexture.dispose();
  95353. }
  95354. if (this.reflectionTexture) {
  95355. this.reflectionTexture.dispose();
  95356. }
  95357. }
  95358. this._renderTargets.dispose();
  95359. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95360. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95361. }
  95362. _super.prototype.dispose.call(this, forceDisposeEffect);
  95363. };
  95364. /**
  95365. * Clones the material.
  95366. * @param name The cloned name.
  95367. * @returns The cloned material.
  95368. */
  95369. BackgroundMaterial.prototype.clone = function (name) {
  95370. var _this = this;
  95371. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  95372. };
  95373. /**
  95374. * Serializes the current material to its JSON representation.
  95375. * @returns The JSON representation.
  95376. */
  95377. BackgroundMaterial.prototype.serialize = function () {
  95378. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95379. serializationObject.customType = "BABYLON.BackgroundMaterial";
  95380. return serializationObject;
  95381. };
  95382. /**
  95383. * Gets the class name of the material
  95384. * @returns "BackgroundMaterial"
  95385. */
  95386. BackgroundMaterial.prototype.getClassName = function () {
  95387. return "BackgroundMaterial";
  95388. };
  95389. /**
  95390. * Parse a JSON input to create back a background material.
  95391. * @param source The JSON data to parse
  95392. * @param scene The scene to create the parsed material in
  95393. * @param rootUrl The root url of the assets the material depends upon
  95394. * @returns the instantiated BackgroundMaterial.
  95395. */
  95396. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  95397. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  95398. };
  95399. /**
  95400. * Standard reflectance value at parallel view angle.
  95401. */
  95402. BackgroundMaterial.StandardReflectance0 = 0.05;
  95403. /**
  95404. * Standard reflectance value at grazing angle.
  95405. */
  95406. BackgroundMaterial.StandardReflectance90 = 0.5;
  95407. /**
  95408. * Tone Mapping calibration (should match image processing tone mapping calibration value).
  95409. */
  95410. BackgroundMaterial._tonemappingCalibration = 1.590579;
  95411. __decorate([
  95412. BABYLON.serializeAsColor3()
  95413. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  95414. __decorate([
  95415. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95416. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  95417. __decorate([
  95418. BABYLON.serializeAsColor3()
  95419. ], BackgroundMaterial.prototype, "_perceptualColor", void 0);
  95420. __decorate([
  95421. BABYLON.serialize()
  95422. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  95423. __decorate([
  95424. BABYLON.serialize()
  95425. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  95426. __decorate([
  95427. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95428. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  95429. __decorate([
  95430. BABYLON.serializeAsTexture()
  95431. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  95432. __decorate([
  95433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95434. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  95435. __decorate([
  95436. BABYLON.serialize()
  95437. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  95438. __decorate([
  95439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95440. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  95441. __decorate([
  95442. BABYLON.serializeAsTexture()
  95443. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  95444. __decorate([
  95445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95446. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  95447. __decorate([
  95448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95449. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  95450. __decorate([
  95451. BABYLON.serialize()
  95452. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  95453. __decorate([
  95454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95455. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  95456. __decorate([
  95457. BABYLON.serializeAsVector3()
  95458. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  95459. __decorate([
  95460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95461. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  95462. __decorate([
  95463. BABYLON.serialize()
  95464. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  95465. __decorate([
  95466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95467. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  95468. __decorate([
  95469. BABYLON.serialize()
  95470. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  95471. __decorate([
  95472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95473. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  95474. __decorate([
  95475. BABYLON.serialize()
  95476. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  95477. __decorate([
  95478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95479. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  95480. __decorate([
  95481. BABYLON.serialize()
  95482. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  95483. __decorate([
  95484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95485. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  95486. __decorate([
  95487. BABYLON.serialize()
  95488. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  95489. __decorate([
  95490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95491. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  95492. __decorate([
  95493. BABYLON.serialize()
  95494. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  95495. __decorate([
  95496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95497. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  95498. __decorate([
  95499. BABYLON.serialize()
  95500. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  95501. __decorate([
  95502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95503. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  95504. __decorate([
  95505. BABYLON.serialize()
  95506. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  95507. __decorate([
  95508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95509. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  95510. __decorate([
  95511. BABYLON.serialize()
  95512. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  95513. __decorate([
  95514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95515. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  95516. __decorate([
  95517. BABYLON.serializeAsImageProcessingConfiguration()
  95518. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  95519. return BackgroundMaterial;
  95520. }(BABYLON.PushMaterial));
  95521. BABYLON.BackgroundMaterial = BackgroundMaterial;
  95522. })(BABYLON || (BABYLON = {}));
  95523. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  95524. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95525. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95526. s = arguments[i];
  95527. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95528. t[p] = s[p];
  95529. }
  95530. return t;
  95531. };
  95532. var BABYLON;
  95533. (function (BABYLON) {
  95534. /**
  95535. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  95536. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  95537. * It also helps with the default setup of your imageProcessing configuration.
  95538. */
  95539. var EnvironmentHelper = /** @class */ (function () {
  95540. /**
  95541. * constructor
  95542. * @param options
  95543. * @param scene The scene to add the material to
  95544. */
  95545. function EnvironmentHelper(options, scene) {
  95546. var _this = this;
  95547. this._errorHandler = function (message, exception) {
  95548. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  95549. };
  95550. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  95551. this._scene = scene;
  95552. this.onErrorObservable = new BABYLON.Observable();
  95553. this._setupBackground();
  95554. this._setupImageProcessing();
  95555. }
  95556. /**
  95557. * Creates the default options for the helper.
  95558. */
  95559. EnvironmentHelper._getDefaultOptions = function () {
  95560. return {
  95561. createGround: true,
  95562. groundSize: 15,
  95563. groundTexture: this._groundTextureCDNUrl,
  95564. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95565. groundOpacity: 0.9,
  95566. enableGroundShadow: true,
  95567. groundShadowLevel: 0.5,
  95568. enableGroundMirror: false,
  95569. groundMirrorSizeRatio: 0.3,
  95570. groundMirrorBlurKernel: 64,
  95571. groundMirrorAmount: 1,
  95572. groundMirrorFresnelWeight: 1,
  95573. groundMirrorFallOffDistance: 0,
  95574. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  95575. groundYBias: 0.00001,
  95576. createSkybox: true,
  95577. skyboxSize: 20,
  95578. skyboxTexture: this._skyboxTextureCDNUrl,
  95579. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95580. backgroundYRotation: 0,
  95581. sizeAuto: true,
  95582. rootPosition: BABYLON.Vector3.Zero(),
  95583. setupImageProcessing: true,
  95584. environmentTexture: this._environmentTextureCDNUrl,
  95585. cameraExposure: 0.8,
  95586. cameraContrast: 1.2,
  95587. toneMappingEnabled: true,
  95588. };
  95589. };
  95590. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  95591. /**
  95592. * Gets the root mesh created by the helper.
  95593. */
  95594. get: function () {
  95595. return this._rootMesh;
  95596. },
  95597. enumerable: true,
  95598. configurable: true
  95599. });
  95600. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  95601. /**
  95602. * Gets the skybox created by the helper.
  95603. */
  95604. get: function () {
  95605. return this._skybox;
  95606. },
  95607. enumerable: true,
  95608. configurable: true
  95609. });
  95610. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  95611. /**
  95612. * Gets the skybox texture created by the helper.
  95613. */
  95614. get: function () {
  95615. return this._skyboxTexture;
  95616. },
  95617. enumerable: true,
  95618. configurable: true
  95619. });
  95620. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  95621. /**
  95622. * Gets the skybox material created by the helper.
  95623. */
  95624. get: function () {
  95625. return this._skyboxMaterial;
  95626. },
  95627. enumerable: true,
  95628. configurable: true
  95629. });
  95630. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  95631. /**
  95632. * Gets the ground mesh created by the helper.
  95633. */
  95634. get: function () {
  95635. return this._ground;
  95636. },
  95637. enumerable: true,
  95638. configurable: true
  95639. });
  95640. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  95641. /**
  95642. * Gets the ground texture created by the helper.
  95643. */
  95644. get: function () {
  95645. return this._groundTexture;
  95646. },
  95647. enumerable: true,
  95648. configurable: true
  95649. });
  95650. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95651. /**
  95652. * Gets the ground mirror created by the helper.
  95653. */
  95654. get: function () {
  95655. return this._groundMirror;
  95656. },
  95657. enumerable: true,
  95658. configurable: true
  95659. });
  95660. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95661. /**
  95662. * Gets the ground mirror render list to helps pushing the meshes
  95663. * you wish in the ground reflection.
  95664. */
  95665. get: function () {
  95666. if (this._groundMirror) {
  95667. return this._groundMirror.renderList;
  95668. }
  95669. return null;
  95670. },
  95671. enumerable: true,
  95672. configurable: true
  95673. });
  95674. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95675. /**
  95676. * Gets the ground material created by the helper.
  95677. */
  95678. get: function () {
  95679. return this._groundMaterial;
  95680. },
  95681. enumerable: true,
  95682. configurable: true
  95683. });
  95684. /**
  95685. * Updates the background according to the new options
  95686. * @param options
  95687. */
  95688. EnvironmentHelper.prototype.updateOptions = function (options) {
  95689. var newOptions = __assign({}, this._options, options);
  95690. if (this._ground && !newOptions.createGround) {
  95691. this._ground.dispose();
  95692. this._ground = null;
  95693. }
  95694. if (this._groundMaterial && !newOptions.createGround) {
  95695. this._groundMaterial.dispose();
  95696. this._groundMaterial = null;
  95697. }
  95698. if (this._groundTexture) {
  95699. if (this._options.groundTexture != newOptions.groundTexture) {
  95700. this._groundTexture.dispose();
  95701. this._groundTexture = null;
  95702. }
  95703. }
  95704. if (this._skybox && !newOptions.createSkybox) {
  95705. this._skybox.dispose();
  95706. this._skybox = null;
  95707. }
  95708. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95709. this._skyboxMaterial.dispose();
  95710. this._skyboxMaterial = null;
  95711. }
  95712. if (this._skyboxTexture) {
  95713. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95714. this._skyboxTexture.dispose();
  95715. this._skyboxTexture = null;
  95716. }
  95717. }
  95718. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95719. this._groundMirror.dispose();
  95720. this._groundMirror = null;
  95721. }
  95722. if (this._scene.environmentTexture) {
  95723. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95724. this._scene.environmentTexture.dispose();
  95725. }
  95726. }
  95727. this._options = newOptions;
  95728. this._setupBackground();
  95729. this._setupImageProcessing();
  95730. };
  95731. /**
  95732. * Sets the primary color of all the available elements.
  95733. * @param color the main color to affect to the ground and the background
  95734. * @param perceptual Specifies wether the chosen color has been set as intented to be seen e.g. in gamma space not accounting for exposure and tone mapping
  95735. */
  95736. EnvironmentHelper.prototype.setMainColor = function (color, perceptual) {
  95737. if (perceptual === void 0) { perceptual = false; }
  95738. if (this.groundMaterial) {
  95739. if (perceptual) {
  95740. this.groundMaterial.perceptualColor = color;
  95741. }
  95742. else {
  95743. this.groundMaterial.primaryColor = color;
  95744. }
  95745. }
  95746. if (this.skyboxMaterial) {
  95747. if (perceptual) {
  95748. this.skyboxMaterial.perceptualColor = color;
  95749. }
  95750. else {
  95751. this.skyboxMaterial.primaryColor = color;
  95752. }
  95753. }
  95754. if (this.groundMirror) {
  95755. if (perceptual && this.groundMaterial) {
  95756. this.groundMirror.clearColor = new BABYLON.Color4(this.groundMaterial.primaryColor.r, this.groundMaterial.primaryColor.g, this.groundMaterial.primaryColor.b, 1.0);
  95757. }
  95758. else {
  95759. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95760. }
  95761. }
  95762. };
  95763. /**
  95764. * Setup the image processing according to the specified options.
  95765. */
  95766. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95767. if (this._options.setupImageProcessing) {
  95768. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95769. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95770. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95771. this._setupEnvironmentTexture();
  95772. }
  95773. };
  95774. /**
  95775. * Setup the environment texture according to the specified options.
  95776. */
  95777. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95778. if (this._scene.environmentTexture) {
  95779. return;
  95780. }
  95781. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95782. this._scene.environmentTexture = this._options.environmentTexture;
  95783. return;
  95784. }
  95785. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95786. this._scene.environmentTexture = environmentTexture;
  95787. };
  95788. /**
  95789. * Setup the background according to the specified options.
  95790. */
  95791. EnvironmentHelper.prototype._setupBackground = function () {
  95792. if (!this._rootMesh) {
  95793. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95794. }
  95795. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95796. var sceneSize = this._getSceneSize();
  95797. if (this._options.createGround) {
  95798. this._setupGround(sceneSize);
  95799. this._setupGroundMaterial();
  95800. this._setupGroundDiffuseTexture();
  95801. if (this._options.enableGroundMirror) {
  95802. this._setupGroundMirrorTexture(sceneSize);
  95803. }
  95804. this._setupMirrorInGroundMaterial();
  95805. }
  95806. if (this._options.createSkybox) {
  95807. this._setupSkybox(sceneSize);
  95808. this._setupSkyboxMaterial();
  95809. this._setupSkyboxReflectionTexture();
  95810. }
  95811. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95812. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95813. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95814. };
  95815. /**
  95816. * Get the scene sizes according to the setup.
  95817. */
  95818. EnvironmentHelper.prototype._getSceneSize = function () {
  95819. var _this = this;
  95820. var groundSize = this._options.groundSize;
  95821. var skyboxSize = this._options.skyboxSize;
  95822. var rootPosition = this._options.rootPosition;
  95823. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  95824. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95825. }
  95826. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95827. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95828. });
  95829. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95830. if (this._options.sizeAuto) {
  95831. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95832. this._scene.activeCamera.upperRadiusLimit) {
  95833. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95834. skyboxSize = groundSize;
  95835. }
  95836. var sceneDiagonalLenght = sceneDiagonal.length();
  95837. if (sceneDiagonalLenght > groundSize) {
  95838. groundSize = sceneDiagonalLenght * 2;
  95839. skyboxSize = groundSize;
  95840. }
  95841. // 10 % bigger.
  95842. groundSize *= 1.1;
  95843. skyboxSize *= 1.5;
  95844. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95845. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95846. }
  95847. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95848. };
  95849. /**
  95850. * Setup the ground according to the specified options.
  95851. */
  95852. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95853. var _this = this;
  95854. if (!this._ground) {
  95855. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95856. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95857. this._ground.parent = this._rootMesh;
  95858. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  95859. }
  95860. this._ground.receiveShadows = this._options.enableGroundShadow;
  95861. };
  95862. /**
  95863. * Setup the ground material according to the specified options.
  95864. */
  95865. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  95866. if (!this._groundMaterial) {
  95867. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  95868. }
  95869. this._groundMaterial.alpha = this._options.groundOpacity;
  95870. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  95871. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  95872. this._groundMaterial.primaryColor = this._options.groundColor;
  95873. this._groundMaterial.useRGBColor = false;
  95874. this._groundMaterial.enableNoise = true;
  95875. if (this._ground) {
  95876. this._ground.material = this._groundMaterial;
  95877. }
  95878. };
  95879. /**
  95880. * Setup the ground diffuse texture according to the specified options.
  95881. */
  95882. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  95883. if (!this._groundMaterial) {
  95884. return;
  95885. }
  95886. if (this._groundTexture) {
  95887. return;
  95888. }
  95889. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  95890. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  95891. return;
  95892. }
  95893. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95894. diffuseTexture.gammaSpace = false;
  95895. diffuseTexture.hasAlpha = true;
  95896. this._groundMaterial.diffuseTexture = diffuseTexture;
  95897. };
  95898. /**
  95899. * Setup the ground mirror texture according to the specified options.
  95900. */
  95901. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  95902. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95903. if (!this._groundMirror) {
  95904. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  95905. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  95906. this._groundMirror.anisotropicFilteringLevel = 1;
  95907. this._groundMirror.wrapU = wrapping;
  95908. this._groundMirror.wrapV = wrapping;
  95909. this._groundMirror.gammaSpace = false;
  95910. if (this._groundMirror.renderList) {
  95911. for (var i = 0; i < this._scene.meshes.length; i++) {
  95912. var mesh = this._scene.meshes[i];
  95913. if (mesh !== this._ground &&
  95914. mesh !== this._skybox &&
  95915. mesh !== this._rootMesh) {
  95916. this._groundMirror.renderList.push(mesh);
  95917. }
  95918. }
  95919. }
  95920. }
  95921. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  95922. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  95923. };
  95924. /**
  95925. * Setup the ground to receive the mirror texture.
  95926. */
  95927. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  95928. if (this._groundMaterial) {
  95929. this._groundMaterial.reflectionTexture = this._groundMirror;
  95930. this._groundMaterial.reflectionFresnel = true;
  95931. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  95932. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  95933. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  95934. }
  95935. };
  95936. /**
  95937. * Setup the skybox according to the specified options.
  95938. */
  95939. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  95940. var _this = this;
  95941. if (!this._skybox) {
  95942. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  95943. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  95944. }
  95945. this._skybox.parent = this._rootMesh;
  95946. };
  95947. /**
  95948. * Setup the skybox material according to the specified options.
  95949. */
  95950. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  95951. if (!this._skybox) {
  95952. return;
  95953. }
  95954. if (!this._skyboxMaterial) {
  95955. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  95956. }
  95957. this._skyboxMaterial.useRGBColor = false;
  95958. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  95959. this._skyboxMaterial.enableNoise = true;
  95960. this._skybox.material = this._skyboxMaterial;
  95961. };
  95962. /**
  95963. * Setup the skybox reflection texture according to the specified options.
  95964. */
  95965. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  95966. if (!this._skyboxMaterial) {
  95967. return;
  95968. }
  95969. if (this._skyboxTexture) {
  95970. return;
  95971. }
  95972. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  95973. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  95974. return;
  95975. }
  95976. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95977. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  95978. this._skyboxTexture.gammaSpace = false;
  95979. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95980. };
  95981. /**
  95982. * Dispose all the elements created by the Helper.
  95983. */
  95984. EnvironmentHelper.prototype.dispose = function () {
  95985. if (this._groundMaterial) {
  95986. this._groundMaterial.dispose(true, true);
  95987. }
  95988. if (this._skyboxMaterial) {
  95989. this._skyboxMaterial.dispose(true, true);
  95990. }
  95991. this._rootMesh.dispose(false);
  95992. };
  95993. /**
  95994. * Default ground texture URL.
  95995. */
  95996. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  95997. /**
  95998. * Default skybox texture URL.
  95999. */
  96000. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96001. /**
  96002. * Default environment texture URL.
  96003. */
  96004. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96005. return EnvironmentHelper;
  96006. }());
  96007. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96008. })(BABYLON || (BABYLON = {}));
  96009. //# sourceMappingURL=babylon.environmentHelper.js.map
  96010. var BABYLON;
  96011. (function (BABYLON) {
  96012. /**
  96013. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96014. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96015. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96016. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96017. */
  96018. var VideoDome = /** @class */ (function (_super) {
  96019. __extends(VideoDome, _super);
  96020. /**
  96021. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96022. * @param name Element's name, child elements will append suffixes for their own names.
  96023. * @param urlsOrVideo
  96024. * @param options An object containing optional or exposed sub element properties:
  96025. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96026. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96027. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96028. * @param options **loop=true** Automatically loop video on end.
  96029. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96030. */
  96031. function VideoDome(name, urlsOrVideo, options, scene) {
  96032. var _this = _super.call(this, name, scene) || this;
  96033. // set defaults and manage values
  96034. name = name || "videoDome";
  96035. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96036. options.clickToPlay = Boolean(options.clickToPlay);
  96037. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96038. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96039. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96040. // create
  96041. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96042. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96043. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96044. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96045. flat: false,
  96046. radius: options.size,
  96047. subdivisions: options.resolution,
  96048. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96049. }, scene);
  96050. // configure material
  96051. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96052. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96053. material.reflectionTexture = _this._videoTexture;
  96054. material.useEquirectangularFOV = true;
  96055. material.fovMultiplier = 1.0;
  96056. // configure mesh
  96057. _this._mesh.material = material;
  96058. _this._mesh.parent = _this;
  96059. // optional configuration
  96060. if (options.clickToPlay) {
  96061. scene.onPointerUp = function () {
  96062. _this._videoTexture.video.play();
  96063. };
  96064. }
  96065. return _this;
  96066. }
  96067. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96068. /**
  96069. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96070. * Also see the options.resolution property.
  96071. */
  96072. get: function () {
  96073. return this._material.fovMultiplier;
  96074. },
  96075. set: function (value) {
  96076. this._material.fovMultiplier = value;
  96077. },
  96078. enumerable: true,
  96079. configurable: true
  96080. });
  96081. /**
  96082. * Releases resources associated with this node.
  96083. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96084. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96085. */
  96086. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96087. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96088. this._videoTexture.dispose();
  96089. this._mesh.dispose();
  96090. this._material.dispose();
  96091. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96092. };
  96093. return VideoDome;
  96094. }(BABYLON.Node));
  96095. BABYLON.VideoDome = VideoDome;
  96096. })(BABYLON || (BABYLON = {}));
  96097. //# sourceMappingURL=babylon.videoDome.js.map
  96098. 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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\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#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#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#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(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}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  96099. 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,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 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,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  96100. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  96101. globalObject["BABYLON"] = BABYLON;
  96102. //backwards compatibility
  96103. if(typeof earcut !== 'undefined') {
  96104. globalObject["Earcut"] = {
  96105. earcut: earcut
  96106. };
  96107. }
  96108. return BABYLON;
  96109. });
  96110. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  96111. /***/ }),
  96112. /* 1 */
  96113. /***/ (function(module, exports, __webpack_require__) {
  96114. "use strict";
  96115. Object.defineProperty(exports, "__esModule", { value: true });
  96116. var babylonjs_1 = __webpack_require__(0);
  96117. var helper_1 = __webpack_require__(3);
  96118. /**
  96119. * This is a simple HTML mapper.
  96120. * This mapper parses a single HTML element and returns the configuration from its attributes.
  96121. * it parses numbers and boolean values to the corresponding variable types.
  96122. * The following HTML element:
  96123. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  96124. *
  96125. * {
  96126. * test: 1, //a number!
  96127. * randomFlag: boolean, //camelCase and boolean
  96128. * a: {
  96129. * string: {
  96130. * object: "test" //dot-separated object levels
  96131. * }
  96132. * }
  96133. * }
  96134. */
  96135. var HTMLMapper = /** @class */ (function () {
  96136. function HTMLMapper() {
  96137. }
  96138. /**
  96139. * Map a specific element and get configuration from it
  96140. * @param element the HTML element to analyze.
  96141. */
  96142. HTMLMapper.prototype.map = function (element) {
  96143. var config = {};
  96144. var _loop_1 = function (attrIdx) {
  96145. var attr = element.attributes.item(attrIdx);
  96146. if (!attr) {
  96147. return "continue";
  96148. }
  96149. // map "object.property" to the right configuration place.
  96150. var split = attr.nodeName.split('.');
  96151. split.reduce(function (currentConfig, key, idx) {
  96152. //convert html-style to json-style
  96153. var camelKey = helper_1.kebabToCamel(key);
  96154. if (idx === split.length - 1) {
  96155. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  96156. if (val === "true") {
  96157. val = true;
  96158. }
  96159. else if (val === "false") {
  96160. val = false;
  96161. }
  96162. else {
  96163. var isnum = /^\d+$/.test(val);
  96164. if (isnum) {
  96165. var number = parseFloat(val);
  96166. if (!isNaN(number)) {
  96167. val = number;
  96168. }
  96169. }
  96170. }
  96171. currentConfig[camelKey] = val;
  96172. }
  96173. else {
  96174. currentConfig[camelKey] = currentConfig[camelKey] || {};
  96175. }
  96176. return currentConfig[camelKey];
  96177. }, config);
  96178. };
  96179. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  96180. _loop_1(attrIdx);
  96181. }
  96182. return config;
  96183. };
  96184. return HTMLMapper;
  96185. }());
  96186. /**
  96187. * A simple string-to-JSON mapper.
  96188. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  96189. */
  96190. var JSONMapper = /** @class */ (function () {
  96191. function JSONMapper() {
  96192. }
  96193. JSONMapper.prototype.map = function (rawSource) {
  96194. return JSON.parse(rawSource);
  96195. };
  96196. return JSONMapper;
  96197. }());
  96198. /**
  96199. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  96200. * DOM elements and attributes.
  96201. */
  96202. var DOMMapper = /** @class */ (function () {
  96203. function DOMMapper() {
  96204. }
  96205. /**
  96206. * The mapping function that will convert HTML data to a viewer configuration object
  96207. * @param baseElement the baseElement from which to start traversing
  96208. * @returns a ViewerCOnfiguration object from the provided HTML Element
  96209. */
  96210. DOMMapper.prototype.map = function (baseElement) {
  96211. var htmlMapper = new HTMLMapper();
  96212. var config = htmlMapper.map(baseElement);
  96213. var traverseChildren = function (element, partConfig) {
  96214. var children = element.children;
  96215. if (children.length) {
  96216. for (var i = 0; i < children.length; ++i) {
  96217. var item = children.item(i);
  96218. // use the HTML Mapper to read configuration from a single element
  96219. var configMapped = htmlMapper.map(item);
  96220. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  96221. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  96222. partConfig[key] = [];
  96223. }
  96224. else {
  96225. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  96226. partConfig.push(configMapped);
  96227. }
  96228. else if (partConfig[key]) {
  96229. //exists already! probably an array
  96230. element.setAttribute('array', 'true');
  96231. var oldItem = partConfig[key];
  96232. partConfig = [oldItem, configMapped];
  96233. }
  96234. else {
  96235. partConfig[key] = configMapped;
  96236. }
  96237. }
  96238. traverseChildren(item, partConfig[key] || configMapped);
  96239. }
  96240. }
  96241. return partConfig;
  96242. };
  96243. traverseChildren(baseElement, config);
  96244. return config;
  96245. };
  96246. return DOMMapper;
  96247. }());
  96248. /**
  96249. * The MapperManager manages the different implemented mappers.
  96250. * It allows the user to register new mappers as well and use them to parse their own configuration data
  96251. */
  96252. var MapperManager = /** @class */ (function () {
  96253. function MapperManager() {
  96254. this._mappers = {
  96255. "html": new HTMLMapper(),
  96256. "json": new JSONMapper(),
  96257. "dom": new DOMMapper()
  96258. };
  96259. }
  96260. /**
  96261. * Get a specific configuration mapper.
  96262. *
  96263. * @param type the name of the mapper to load
  96264. */
  96265. MapperManager.prototype.getMapper = function (type) {
  96266. if (!this._mappers[type]) {
  96267. babylonjs_1.Tools.Error("No mapper defined for " + type);
  96268. }
  96269. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  96270. };
  96271. /**
  96272. * Use this functio to register your own configuration mapper.
  96273. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  96274. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  96275. * @param mapper The implemented mapper
  96276. */
  96277. MapperManager.prototype.registerMapper = function (type, mapper) {
  96278. this._mappers[type] = mapper;
  96279. };
  96280. /**
  96281. * Dispose the mapper manager and all of its mappers.
  96282. */
  96283. MapperManager.prototype.dispose = function () {
  96284. this._mappers = {};
  96285. };
  96286. /**
  96287. * The default mapper is the JSON mapper.
  96288. */
  96289. MapperManager.DefaultMapper = 'json';
  96290. return MapperManager;
  96291. }());
  96292. exports.MapperManager = MapperManager;
  96293. /**
  96294. * mapperManager is a singleton of the type MapperManager.
  96295. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  96296. * or indirectly with using BabylonViewer.disposeAll()
  96297. */
  96298. exports.mapperManager = new MapperManager();
  96299. /***/ }),
  96300. /* 2 */
  96301. /***/ (function(module, exports, __webpack_require__) {
  96302. (function (global, factory) {
  96303. true ? module.exports = factory() :
  96304. typeof define === 'function' && define.amd ? define(factory) :
  96305. (global.deepmerge = factory());
  96306. }(this, (function () { 'use strict';
  96307. var isMergeableObject = function isMergeableObject(value) {
  96308. return isNonNullObject(value)
  96309. && !isSpecial(value)
  96310. };
  96311. function isNonNullObject(value) {
  96312. return !!value && typeof value === 'object'
  96313. }
  96314. function isSpecial(value) {
  96315. var stringValue = Object.prototype.toString.call(value);
  96316. return stringValue === '[object RegExp]'
  96317. || stringValue === '[object Date]'
  96318. || isReactElement(value)
  96319. }
  96320. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  96321. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  96322. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  96323. function isReactElement(value) {
  96324. return value.$$typeof === REACT_ELEMENT_TYPE
  96325. }
  96326. function emptyTarget(val) {
  96327. return Array.isArray(val) ? [] : {}
  96328. }
  96329. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  96330. var clone = !optionsArgument || optionsArgument.clone !== false;
  96331. return (clone && isMergeableObject(value))
  96332. ? deepmerge(emptyTarget(value), value, optionsArgument)
  96333. : value
  96334. }
  96335. function defaultArrayMerge(target, source, optionsArgument) {
  96336. return target.concat(source).map(function(element) {
  96337. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  96338. })
  96339. }
  96340. function mergeObject(target, source, optionsArgument) {
  96341. var destination = {};
  96342. if (isMergeableObject(target)) {
  96343. Object.keys(target).forEach(function(key) {
  96344. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  96345. });
  96346. }
  96347. Object.keys(source).forEach(function(key) {
  96348. if (!isMergeableObject(source[key]) || !target[key]) {
  96349. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  96350. } else {
  96351. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  96352. }
  96353. });
  96354. return destination
  96355. }
  96356. function deepmerge(target, source, optionsArgument) {
  96357. var sourceIsArray = Array.isArray(source);
  96358. var targetIsArray = Array.isArray(target);
  96359. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  96360. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  96361. if (!sourceAndTargetTypesMatch) {
  96362. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  96363. } else if (sourceIsArray) {
  96364. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  96365. return arrayMerge(target, source, optionsArgument)
  96366. } else {
  96367. return mergeObject(target, source, optionsArgument)
  96368. }
  96369. }
  96370. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  96371. if (!Array.isArray(array)) {
  96372. throw new Error('first argument should be an array')
  96373. }
  96374. return array.reduce(function(prev, next) {
  96375. return deepmerge(prev, next, optionsArgument)
  96376. }, {})
  96377. };
  96378. var deepmerge_1 = deepmerge;
  96379. return deepmerge_1;
  96380. })));
  96381. /***/ }),
  96382. /* 3 */
  96383. /***/ (function(module, exports, __webpack_require__) {
  96384. "use strict";
  96385. Object.defineProperty(exports, "__esModule", { value: true });
  96386. /**
  96387. * Is the provided string a URL?
  96388. *
  96389. * @param urlToCheck the url to inspect
  96390. */
  96391. function isUrl(urlToCheck) {
  96392. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  96393. return true;
  96394. }
  96395. return false;
  96396. }
  96397. exports.isUrl = isUrl;
  96398. /**
  96399. * Convert a string from kebab-case to camelCase
  96400. * @param s string to convert
  96401. */
  96402. function kebabToCamel(s) {
  96403. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  96404. }
  96405. exports.kebabToCamel = kebabToCamel;
  96406. //https://gist.github.com/youssman/745578062609e8acac9f
  96407. /**
  96408. * Convert a string from camelCase to kebab-case
  96409. * @param str string to convert
  96410. */
  96411. function camelToKebab(str) {
  96412. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  96413. }
  96414. exports.camelToKebab = camelToKebab;
  96415. /***/ }),
  96416. /* 4 */
  96417. /***/ (function(module, exports, __webpack_require__) {
  96418. "use strict";
  96419. Object.defineProperty(exports, "__esModule", { value: true });
  96420. var babylonjs_1 = __webpack_require__(0);
  96421. /**
  96422. * The viewer manager is the container for all viewers currently registered on this page.
  96423. * It is possible to have more than one viewer on a single page.
  96424. */
  96425. var ViewerManager = /** @class */ (function () {
  96426. function ViewerManager() {
  96427. this._viewers = {};
  96428. this.onViewerAddedObservable = new babylonjs_1.Observable();
  96429. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  96430. }
  96431. /**
  96432. * Adding a new viewer to the viewer manager and start tracking it.
  96433. * @param viewer the viewer to add
  96434. */
  96435. ViewerManager.prototype.addViewer = function (viewer) {
  96436. this._viewers[viewer.getBaseId()] = viewer;
  96437. this._onViewerAdded(viewer);
  96438. };
  96439. /**
  96440. * remove a viewer from the viewer manager
  96441. * @param viewer the viewer to remove
  96442. */
  96443. ViewerManager.prototype.removeViewer = function (viewer) {
  96444. var id = viewer.getBaseId();
  96445. delete this._viewers[id];
  96446. this.onViewerRemovedObservable.notifyObservers(id);
  96447. };
  96448. /**
  96449. * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned)
  96450. * @param id the id of the HTMl element (or the viewer's, if none provided)
  96451. */
  96452. ViewerManager.prototype.getViewerById = function (id) {
  96453. return this._viewers[id];
  96454. };
  96455. /**
  96456. * Get a viewer using a container element
  96457. * @param element the HTML element to search viewers associated with
  96458. */
  96459. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  96460. for (var id in this._viewers) {
  96461. if (this._viewers[id].containerElement === element) {
  96462. return this.getViewerById(id);
  96463. }
  96464. }
  96465. };
  96466. /**
  96467. * Get a promise that will fullfil when this viewer was initialized.
  96468. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  96469. * you will get the viewer after everything was already configured.
  96470. * @param id the viewer id to find
  96471. */
  96472. ViewerManager.prototype.getViewerPromiseById = function (id) {
  96473. var _this = this;
  96474. return new Promise(function (resolve, reject) {
  96475. var localViewer = _this.getViewerById(id);
  96476. if (localViewer) {
  96477. return resolve(localViewer);
  96478. }
  96479. var viewerFunction = function (viewer) {
  96480. if (viewer.getBaseId() === id) {
  96481. resolve(viewer);
  96482. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  96483. }
  96484. };
  96485. _this.onViewerAddedObservable.add(viewerFunction);
  96486. });
  96487. };
  96488. ViewerManager.prototype._onViewerAdded = function (viewer) {
  96489. this.onViewerAdded && this.onViewerAdded(viewer);
  96490. this.onViewerAddedObservable.notifyObservers(viewer);
  96491. };
  96492. /**
  96493. * dispose the manager and all of its associated viewers
  96494. */
  96495. ViewerManager.prototype.dispose = function () {
  96496. for (var id in this._viewers) {
  96497. this._viewers[id].dispose();
  96498. }
  96499. };
  96500. return ViewerManager;
  96501. }());
  96502. exports.ViewerManager = ViewerManager;
  96503. exports.viewerManager = new ViewerManager();
  96504. /***/ }),
  96505. /* 5 */
  96506. /***/ (function(module, exports, __webpack_require__) {
  96507. "use strict";
  96508. var __extends = (this && this.__extends) || (function () {
  96509. var extendStatics = Object.setPrototypeOf ||
  96510. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  96511. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  96512. return function (d, b) {
  96513. extendStatics(d, b);
  96514. function __() { this.constructor = d; }
  96515. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  96516. };
  96517. })();
  96518. Object.defineProperty(exports, "__esModule", { value: true });
  96519. var viewer_1 = __webpack_require__(6);
  96520. var babylonjs_1 = __webpack_require__(0);
  96521. /**
  96522. * The Default viewer is the default implementation of the AbstractViewer.
  96523. * It uses the templating system to render a new canvas and controls.
  96524. */
  96525. var DefaultViewer = /** @class */ (function (_super) {
  96526. __extends(DefaultViewer, _super);
  96527. /**
  96528. * Create a new default viewer
  96529. * @param containerElement the element in which the templates will be rendered
  96530. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  96531. */
  96532. function DefaultViewer(containerElement, initialConfiguration) {
  96533. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  96534. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  96535. _this.containerElement = containerElement;
  96536. _this._onModelLoaded = function (model) {
  96537. _this._configureTemplate(model);
  96538. // with a short timeout, making sure everything is there already.
  96539. var hideLoadingDelay = 500;
  96540. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  96541. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  96542. }
  96543. setTimeout(function () {
  96544. _this.hideLoadingScreen();
  96545. }, hideLoadingDelay);
  96546. return;
  96547. };
  96548. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  96549. return _this;
  96550. }
  96551. /**
  96552. * Overriding the AbstractViewer's _initScene fcuntion
  96553. */
  96554. DefaultViewer.prototype._initScene = function () {
  96555. var _this = this;
  96556. return _super.prototype._initScene.call(this).then(function () {
  96557. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  96558. return _this.scene;
  96559. });
  96560. };
  96561. /**
  96562. * This will be executed when the templates initialize.
  96563. */
  96564. DefaultViewer.prototype._onTemplatesLoaded = function () {
  96565. var _this = this;
  96566. this.showLoadingScreen();
  96567. // navbar
  96568. this._initNavbar();
  96569. // close overlay button
  96570. var closeButton = document.getElementById('close-button');
  96571. if (closeButton) {
  96572. closeButton.addEventListener('pointerdown', function () {
  96573. _this.hideOverlayScreen();
  96574. });
  96575. }
  96576. return _super.prototype._onTemplatesLoaded.call(this);
  96577. };
  96578. DefaultViewer.prototype._initNavbar = function () {
  96579. var navbar = this.templateManager.getTemplate('navBar');
  96580. if (navbar) {
  96581. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  96582. var navbarShown_1 = true;
  96583. var timeoutCancel_1 /*: number*/;
  96584. var triggerNavbar = function (show, evt) {
  96585. if (show === void 0) { show = false; }
  96586. // only left-click on no-button.
  96587. if (!navbar || evt.button > 0)
  96588. return;
  96589. // clear timeout
  96590. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  96591. // if state is the same, do nothing
  96592. if (show === navbarShown_1)
  96593. return;
  96594. //showing? simply show it!
  96595. if (show) {
  96596. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  96597. navbarShown_1 = show;
  96598. }
  96599. else {
  96600. var visibilityTimeout = 2000;
  96601. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  96602. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  96603. }
  96604. // not showing? set timeout until it is removed.
  96605. timeoutCancel_1 = setTimeout(function () {
  96606. if (navbar) {
  96607. navbar.parent.style.bottom = '-' + navbarHeight_1;
  96608. }
  96609. navbarShown_1 = show;
  96610. }, visibilityTimeout);
  96611. }
  96612. };
  96613. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  96614. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  96615. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  96616. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  96617. // other events
  96618. var viewerTemplate = this.templateManager.getTemplate('viewer');
  96619. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  96620. // full screen
  96621. var triggerFullscren = function (eventData) {
  96622. if (viewerElement_1) {
  96623. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  96624. if (!fullscreenElement) {
  96625. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  96626. requestFullScreen.call(viewerElement_1);
  96627. }
  96628. else {
  96629. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  96630. exitFullscreen.call(document);
  96631. }
  96632. }
  96633. };
  96634. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  96635. }
  96636. };
  96637. /**
  96638. * Preparing the container element to present the viewer
  96639. */
  96640. DefaultViewer.prototype._prepareContainerElement = function () {
  96641. this.containerElement.style.position = 'relative';
  96642. this.containerElement.style.display = 'flex';
  96643. };
  96644. /**
  96645. * This function will configure the templates and update them after a model was loaded
  96646. * It is mainly responsible to changing the title and subtitle etc'.
  96647. * @param model the model to be used to configure the templates by
  96648. */
  96649. DefaultViewer.prototype._configureTemplate = function (model) {
  96650. var navbar = this.templateManager.getTemplate('navBar');
  96651. if (!navbar)
  96652. return;
  96653. var modelConfiguration = model.configuration;
  96654. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  96655. if (metadataContainer) {
  96656. if (modelConfiguration.title !== undefined) {
  96657. var element = metadataContainer.querySelector('span.model-title');
  96658. if (element) {
  96659. element.innerHTML = modelConfiguration.title;
  96660. }
  96661. }
  96662. if (modelConfiguration.subtitle !== undefined) {
  96663. var element = metadataContainer.querySelector('span.model-subtitle');
  96664. if (element) {
  96665. element.innerHTML = modelConfiguration.subtitle;
  96666. }
  96667. }
  96668. if (modelConfiguration.thumbnail !== undefined) {
  96669. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  96670. }
  96671. }
  96672. };
  96673. /**
  96674. * This will load a new model to the default viewer
  96675. * overriding the AbstractViewer's loadModel.
  96676. * The scene will automatically be cleared of the old models, if exist.
  96677. * @param model the configuration object (or URL) to load.
  96678. */
  96679. DefaultViewer.prototype.loadModel = function (model) {
  96680. var _this = this;
  96681. if (model === void 0) { model = this._configuration.model; }
  96682. this.showLoadingScreen();
  96683. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  96684. console.log(error);
  96685. _this.hideLoadingScreen();
  96686. _this.showOverlayScreen('error');
  96687. return Promise.reject(error);
  96688. });
  96689. };
  96690. /**
  96691. * Show the overlay and the defined sub-screen.
  96692. * Mainly used for help and errors
  96693. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  96694. */
  96695. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  96696. var _this = this;
  96697. var template = this.templateManager.getTemplate('overlay');
  96698. if (!template)
  96699. return Promise.resolve('Overlay template not found');
  96700. return template.show((function (template) {
  96701. var canvasRect = _this.containerElement.getBoundingClientRect();
  96702. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  96703. template.parent.style.display = 'flex';
  96704. template.parent.style.width = canvasRect.width + "px";
  96705. template.parent.style.height = canvasRect.height + "px";
  96706. template.parent.style.opacity = "1";
  96707. var subTemplate = _this.templateManager.getTemplate(subScreen);
  96708. if (!subTemplate) {
  96709. return Promise.reject(subScreen + ' template not found');
  96710. }
  96711. return subTemplate.show((function (template) {
  96712. template.parent.style.display = 'flex';
  96713. return Promise.resolve(template);
  96714. }));
  96715. }));
  96716. };
  96717. /**
  96718. * Hide the overlay screen.
  96719. */
  96720. DefaultViewer.prototype.hideOverlayScreen = function () {
  96721. var template = this.templateManager.getTemplate('overlay');
  96722. if (!template)
  96723. return Promise.resolve('Overlay template not found');
  96724. return template.hide((function (template) {
  96725. template.parent.style.opacity = "0";
  96726. var onTransitionEnd = function () {
  96727. template.parent.removeEventListener("transitionend", onTransitionEnd);
  96728. template.parent.style.display = 'none';
  96729. };
  96730. template.parent.addEventListener("transitionend", onTransitionEnd);
  96731. var overlays = template.parent.querySelectorAll('.overlay');
  96732. if (overlays) {
  96733. for (var i = 0; i < overlays.length; ++i) {
  96734. var htmlElement = overlays.item(i);
  96735. htmlElement.style.display = 'none';
  96736. }
  96737. }
  96738. return Promise.resolve(template);
  96739. }));
  96740. };
  96741. /**
  96742. * Show the loading screen.
  96743. * The loading screen can be configured using the configuration object
  96744. */
  96745. DefaultViewer.prototype.showLoadingScreen = function () {
  96746. var _this = this;
  96747. var template = this.templateManager.getTemplate('loadingScreen');
  96748. if (!template)
  96749. return Promise.resolve('Loading Screen template not found');
  96750. return template.show((function (template) {
  96751. var canvasRect = _this.containerElement.getBoundingClientRect();
  96752. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  96753. template.parent.style.display = 'flex';
  96754. template.parent.style.width = canvasRect.width + "px";
  96755. template.parent.style.height = canvasRect.height + "px";
  96756. template.parent.style.opacity = "1";
  96757. // from the configuration!!!
  96758. template.parent.style.backgroundColor = "black";
  96759. return Promise.resolve(template);
  96760. }));
  96761. };
  96762. /**
  96763. * Hide the loading screen
  96764. */
  96765. DefaultViewer.prototype.hideLoadingScreen = function () {
  96766. var template = this.templateManager.getTemplate('loadingScreen');
  96767. if (!template)
  96768. return Promise.resolve('Loading Screen template not found');
  96769. return template.hide((function (template) {
  96770. template.parent.style.opacity = "0";
  96771. var onTransitionEnd = function () {
  96772. template.parent.removeEventListener("transitionend", onTransitionEnd);
  96773. template.parent.style.display = 'none';
  96774. };
  96775. template.parent.addEventListener("transitionend", onTransitionEnd);
  96776. return Promise.resolve(template);
  96777. }));
  96778. };
  96779. /**
  96780. * An extension of the light configuration of the abstract viewer.
  96781. * @param lightsConfiguration the light configuration to use
  96782. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  96783. */
  96784. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  96785. var _this = this;
  96786. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  96787. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  96788. // labs feature - flashlight
  96789. if (this._configuration.lab && this._configuration.lab.flashlight) {
  96790. var pointerPosition = babylonjs_1.Vector3.Zero();
  96791. var lightTarget_1;
  96792. var angle = 0.5;
  96793. var exponent = Math.PI / 2;
  96794. if (typeof this._configuration.lab.flashlight === "object") {
  96795. exponent = this._configuration.lab.flashlight.exponent || exponent;
  96796. angle = this._configuration.lab.flashlight.angle || angle;
  96797. }
  96798. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  96799. if (typeof this._configuration.lab.flashlight === "object") {
  96800. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  96801. if (this._configuration.lab.flashlight.diffuse) {
  96802. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  96803. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  96804. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  96805. }
  96806. if (this._configuration.lab.flashlight.specular) {
  96807. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  96808. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  96809. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  96810. }
  96811. }
  96812. this.scene.constantlyUpdateMeshUnderPointer = true;
  96813. this.scene.onPointerObservable.add(function (eventData, eventState) {
  96814. if (eventData.type === 4 && eventData.pickInfo) {
  96815. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  96816. }
  96817. else {
  96818. lightTarget_1 = undefined;
  96819. }
  96820. });
  96821. var updateFlashlightFunction = function () {
  96822. if (_this.camera && flashlight) {
  96823. flashlight.position.copyFrom(_this.camera.position);
  96824. if (lightTarget_1) {
  96825. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  96826. }
  96827. }
  96828. };
  96829. this.scene.registerBeforeRender(updateFlashlightFunction);
  96830. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  96831. }
  96832. };
  96833. return DefaultViewer;
  96834. }(viewer_1.AbstractViewer));
  96835. exports.DefaultViewer = DefaultViewer;
  96836. /***/ }),
  96837. /* 6 */
  96838. /***/ (function(module, exports, __webpack_require__) {
  96839. "use strict";
  96840. Object.defineProperty(exports, "__esModule", { value: true });
  96841. var viewerManager_1 = __webpack_require__(4);
  96842. var templateManager_1 = __webpack_require__(23);
  96843. var loader_1 = __webpack_require__(26);
  96844. var babylonjs_1 = __webpack_require__(0);
  96845. var deepmerge = __webpack_require__(2);
  96846. var modelLoader_1 = __webpack_require__(14);
  96847. /**
  96848. * The AbstractViewr is the center of Babylon's viewer.
  96849. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  96850. */
  96851. var AbstractViewer = /** @class */ (function () {
  96852. function AbstractViewer(containerElement, initialConfiguration) {
  96853. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  96854. var _this = this;
  96855. this.containerElement = containerElement;
  96856. /**
  96857. * is this viewer disposed?
  96858. */
  96859. this._isDisposed = false;
  96860. /**
  96861. * The resize function that will be registered with the window object
  96862. */
  96863. this._resize = function () {
  96864. // Only resize if Canvas is in the DOM
  96865. if (!_this.isCanvasInDOM()) {
  96866. return;
  96867. }
  96868. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  96869. return;
  96870. }
  96871. _this.engine.resize();
  96872. };
  96873. /**
  96874. * render loop that will be executed by the engine
  96875. */
  96876. this._render = function () {
  96877. _this.scene && _this.scene.activeCamera && _this.scene.render();
  96878. };
  96879. // if exists, use the container id. otherwise, generate a random string.
  96880. if (containerElement.id) {
  96881. this.baseId = containerElement.id;
  96882. }
  96883. else {
  96884. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  96885. }
  96886. this.onSceneInitObservable = new babylonjs_1.Observable();
  96887. this.onEngineInitObservable = new babylonjs_1.Observable();
  96888. this.onModelLoadedObservable = new babylonjs_1.Observable();
  96889. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  96890. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  96891. this.onInitDoneObservable = new babylonjs_1.Observable();
  96892. this.onLoaderInitObservable = new babylonjs_1.Observable();
  96893. this._registeredOnBeforeRenderFunctions = [];
  96894. this.models = [];
  96895. this.modelLoader = new modelLoader_1.ModelLoader(this);
  96896. // add this viewer to the viewer manager
  96897. viewerManager_1.viewerManager.addViewer(this);
  96898. // create a new template manager. TODO - singleton?
  96899. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  96900. this._prepareContainerElement();
  96901. // extend the configuration
  96902. this._configurationLoader = new loader_1.ConfigurationLoader();
  96903. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  96904. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  96905. if (_this._configuration.observers) {
  96906. _this._configureObservers(_this._configuration.observers);
  96907. }
  96908. //this.updateConfiguration(configuration);
  96909. // initialize the templates
  96910. var templateConfiguration = _this._configuration.templates || {};
  96911. _this.templateManager.initTemplate(templateConfiguration);
  96912. // when done, execute onTemplatesLoaded()
  96913. _this.templateManager.onAllLoaded.add(function () {
  96914. var canvas = _this.templateManager.getCanvas();
  96915. if (canvas) {
  96916. _this._canvas = canvas;
  96917. }
  96918. _this._onTemplateLoaded();
  96919. });
  96920. });
  96921. }
  96922. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  96923. /**
  96924. * Returns a boolean representing HDR support
  96925. */
  96926. get: function () {
  96927. return this._hdrSupport;
  96928. },
  96929. enumerable: true,
  96930. configurable: true
  96931. });
  96932. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  96933. /**
  96934. * The (single) canvas of this viewer
  96935. */
  96936. get: function () {
  96937. return this._canvas;
  96938. },
  96939. enumerable: true,
  96940. configurable: true
  96941. });
  96942. /**
  96943. * get the baseId of this viewer
  96944. */
  96945. AbstractViewer.prototype.getBaseId = function () {
  96946. return this.baseId;
  96947. };
  96948. /**
  96949. * Do we have a canvas to render on, and is it a part of the scene
  96950. */
  96951. AbstractViewer.prototype.isCanvasInDOM = function () {
  96952. return !!this._canvas && !!this._canvas.parentElement;
  96953. };
  96954. /**
  96955. * Update the current viewer configuration with new values.
  96956. * Only provided information will be updated, old configuration values will be kept.
  96957. * If this.configuration was manually changed, you can trigger this function with no parameters,
  96958. * and the entire configuration will be updated.
  96959. * @param newConfiguration
  96960. */
  96961. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  96962. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  96963. // update this.configuration with the new data
  96964. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  96965. // update scene configuration
  96966. if (newConfiguration.scene) {
  96967. this._configureScene(newConfiguration.scene);
  96968. }
  96969. // optimizer
  96970. if (newConfiguration.optimizer) {
  96971. this._configureOptimizer(newConfiguration.optimizer);
  96972. }
  96973. // observers in configuration
  96974. if (newConfiguration.observers) {
  96975. this._configureObservers(newConfiguration.observers);
  96976. }
  96977. // configure model
  96978. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  96979. this._configureModel(newConfiguration.model);
  96980. }
  96981. // lights
  96982. if (newConfiguration.lights) {
  96983. this._configureLights(newConfiguration.lights);
  96984. }
  96985. // environment
  96986. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  96987. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  96988. }
  96989. // camera
  96990. if (newConfiguration.camera) {
  96991. this._configureCamera(newConfiguration.camera);
  96992. }
  96993. };
  96994. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  96995. if (!skyboxConifguration && !groundConfiguration) {
  96996. if (this.environmentHelper) {
  96997. this.environmentHelper.dispose();
  96998. delete this.environmentHelper;
  96999. }
  97000. ;
  97001. return Promise.resolve(this.scene);
  97002. }
  97003. var options = {
  97004. createGround: !!groundConfiguration,
  97005. createSkybox: !!skyboxConifguration,
  97006. setupImageProcessing: false // will be done at the scene level!
  97007. };
  97008. if (groundConfiguration) {
  97009. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  97010. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  97011. if (groundSize) {
  97012. options.groundSize = groundSize;
  97013. }
  97014. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  97015. if (groundConfig.shadowLevel !== undefined) {
  97016. options.groundShadowLevel = groundConfig.shadowLevel;
  97017. }
  97018. options.enableGroundMirror = !!groundConfig.mirror;
  97019. if (groundConfig.texture) {
  97020. options.groundTexture = groundConfig.texture;
  97021. }
  97022. if (groundConfig.color) {
  97023. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  97024. }
  97025. if (groundConfig.opacity !== undefined) {
  97026. options.groundOpacity = groundConfig.opacity;
  97027. }
  97028. if (groundConfig.mirror) {
  97029. options.enableGroundMirror = true;
  97030. // to prevent undefines
  97031. if (typeof groundConfig.mirror === "object") {
  97032. if (groundConfig.mirror.amount !== undefined)
  97033. options.groundMirrorAmount = groundConfig.mirror.amount;
  97034. if (groundConfig.mirror.sizeRatio !== undefined)
  97035. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  97036. if (groundConfig.mirror.blurKernel !== undefined)
  97037. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  97038. if (groundConfig.mirror.fresnelWeight !== undefined)
  97039. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  97040. if (groundConfig.mirror.fallOffDistance !== undefined)
  97041. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  97042. if (this._defaultPipelineTextureType !== undefined)
  97043. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  97044. }
  97045. }
  97046. }
  97047. var postInitSkyboxMaterial = false;
  97048. if (skyboxConifguration) {
  97049. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  97050. if (conf.material && conf.material.imageProcessingConfiguration) {
  97051. options.setupImageProcessing = false; // will be configured later manually.
  97052. }
  97053. var skyboxSize = conf.scale;
  97054. if (skyboxSize) {
  97055. options.skyboxSize = skyboxSize;
  97056. }
  97057. options.sizeAuto = !options.skyboxSize;
  97058. if (conf.color) {
  97059. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  97060. }
  97061. if (conf.cubeTexture && conf.cubeTexture.url) {
  97062. if (typeof conf.cubeTexture.url === "string") {
  97063. options.skyboxTexture = conf.cubeTexture.url;
  97064. }
  97065. else {
  97066. // init later!
  97067. postInitSkyboxMaterial = true;
  97068. }
  97069. }
  97070. if (conf.material && conf.material.imageProcessingConfiguration) {
  97071. postInitSkyboxMaterial = true;
  97072. }
  97073. }
  97074. options.setupImageProcessing = false; // TMP
  97075. if (!this.environmentHelper) {
  97076. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97077. }
  97078. else {
  97079. // there might be a new scene! we need to dispose.
  97080. // get the scene used by the envHelper
  97081. var scene = this.environmentHelper.rootMesh.getScene();
  97082. // is it a different scene? Oh no!
  97083. if (scene !== this.scene) {
  97084. this.environmentHelper.dispose();
  97085. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97086. }
  97087. else {
  97088. this.environmentHelper.updateOptions(options);
  97089. }
  97090. }
  97091. if (postInitSkyboxMaterial) {
  97092. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  97093. if (skyboxMaterial) {
  97094. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  97095. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  97096. }
  97097. }
  97098. }
  97099. };
  97100. /**
  97101. * internally configure the scene using the provided configuration.
  97102. * The scene will not be recreated, but just updated.
  97103. * @param sceneConfig the (new) scene configuration
  97104. */
  97105. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  97106. // sanity check!
  97107. if (!this.scene) {
  97108. return;
  97109. }
  97110. if (sceneConfig.debug) {
  97111. this.scene.debugLayer.show();
  97112. }
  97113. else {
  97114. if (this.scene.debugLayer.isVisible()) {
  97115. this.scene.debugLayer.hide();
  97116. }
  97117. }
  97118. if (sceneConfig.clearColor) {
  97119. var cc = sceneConfig.clearColor;
  97120. var oldcc = this.scene.clearColor;
  97121. if (cc.r !== undefined) {
  97122. oldcc.r = cc.r;
  97123. }
  97124. if (cc.g !== undefined) {
  97125. oldcc.g = cc.g;
  97126. }
  97127. if (cc.b !== undefined) {
  97128. oldcc.b = cc.b;
  97129. }
  97130. if (cc.a !== undefined) {
  97131. oldcc.a = cc.a;
  97132. }
  97133. }
  97134. // image processing configuration - optional.
  97135. if (sceneConfig.imageProcessingConfiguration) {
  97136. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  97137. }
  97138. if (sceneConfig.environmentTexture) {
  97139. if (this.scene.environmentTexture) {
  97140. this.scene.environmentTexture.dispose();
  97141. }
  97142. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  97143. this.scene.environmentTexture = environmentTexture;
  97144. }
  97145. if (sceneConfig.autoRotate) {
  97146. this.camera.useAutoRotationBehavior = true;
  97147. }
  97148. };
  97149. /**
  97150. * Configure the scene optimizer.
  97151. * The existing scene optimizer will be disposed and a new one will be created.
  97152. * @param optimizerConfig the (new) optimizer configuration
  97153. */
  97154. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  97155. if (typeof optimizerConfig === 'boolean') {
  97156. if (this.sceneOptimizer) {
  97157. this.sceneOptimizer.stop();
  97158. this.sceneOptimizer.dispose();
  97159. delete this.sceneOptimizer;
  97160. }
  97161. if (optimizerConfig) {
  97162. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  97163. this.sceneOptimizer.start();
  97164. }
  97165. }
  97166. else {
  97167. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  97168. // check for degradation
  97169. if (optimizerConfig.degradation) {
  97170. switch (optimizerConfig.degradation) {
  97171. case "low":
  97172. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  97173. break;
  97174. case "moderate":
  97175. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  97176. break;
  97177. case "hight":
  97178. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  97179. break;
  97180. }
  97181. }
  97182. if (this.sceneOptimizer) {
  97183. this.sceneOptimizer.stop();
  97184. this.sceneOptimizer.dispose();
  97185. }
  97186. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  97187. this.sceneOptimizer.start();
  97188. }
  97189. };
  97190. /**
  97191. * this is used to register native functions using the configuration object.
  97192. * This will configure the observers.
  97193. * @param observersConfiguration observers configuration
  97194. */
  97195. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  97196. if (observersConfiguration.onEngineInit) {
  97197. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  97198. }
  97199. else {
  97200. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  97201. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  97202. }
  97203. }
  97204. if (observersConfiguration.onSceneInit) {
  97205. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  97206. }
  97207. else {
  97208. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  97209. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  97210. }
  97211. }
  97212. if (observersConfiguration.onModelLoaded) {
  97213. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  97214. }
  97215. else {
  97216. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  97217. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  97218. }
  97219. }
  97220. };
  97221. /**
  97222. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  97223. * @param cameraConfig the new camera configuration
  97224. * @param model optionally use the model to configure the camera.
  97225. */
  97226. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  97227. var _this = this;
  97228. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97229. if (!this.scene.activeCamera) {
  97230. this.scene.createDefaultCamera(true, true, true);
  97231. this.camera = this.scene.activeCamera;
  97232. }
  97233. if (cameraConfig.position) {
  97234. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  97235. }
  97236. if (cameraConfig.rotation) {
  97237. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  97238. }
  97239. this._extendClassWithConfig(this.camera, cameraConfig);
  97240. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  97241. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  97242. if (cameraConfig.behaviors) {
  97243. for (var name_1 in cameraConfig.behaviors) {
  97244. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  97245. }
  97246. }
  97247. ;
  97248. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  97249. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  97250. });
  97251. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97252. var sceneDiagonalLenght = sceneDiagonal.length();
  97253. if (isFinite(sceneDiagonalLenght))
  97254. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  97255. };
  97256. /**
  97257. * configure the lights.
  97258. *
  97259. * @param lightsConfiguration the (new) light(s) configuration
  97260. * @param model optionally use the model to configure the camera.
  97261. */
  97262. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  97263. var _this = this;
  97264. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  97265. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97266. // sanity check!
  97267. if (!Object.keys(lightsConfiguration).length)
  97268. return;
  97269. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  97270. // compare to the global (!) configuration object and dispose unneeded:
  97271. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  97272. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  97273. lightsAvailable.forEach(function (lName) {
  97274. if (lightsToConfigure.indexOf(lName) === -1) {
  97275. _this.scene.getLightByName(lName).dispose();
  97276. }
  97277. });
  97278. }
  97279. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  97280. var lightConfig = { type: 0 };
  97281. if (typeof lightsConfiguration[name] === 'object') {
  97282. lightConfig = lightsConfiguration[name];
  97283. }
  97284. lightConfig.name = name;
  97285. var light;
  97286. // light is not already available
  97287. if (lightsAvailable.indexOf(name) === -1) {
  97288. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97289. if (!constructor)
  97290. return;
  97291. light = constructor();
  97292. }
  97293. else {
  97294. // available? get it from the scene
  97295. light = _this.scene.getLightByName(name);
  97296. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  97297. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  97298. light.dispose();
  97299. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97300. if (!constructor)
  97301. return;
  97302. light = constructor();
  97303. }
  97304. }
  97305. // if config set the light to false, dispose it.
  97306. if (lightsConfiguration[name] === false) {
  97307. light.dispose();
  97308. return;
  97309. }
  97310. //enabled
  97311. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  97312. light.setEnabled(enabled);
  97313. _this._extendClassWithConfig(light, lightConfig);
  97314. //position. Some lights don't support shadows
  97315. if (light instanceof babylonjs_1.ShadowLight) {
  97316. if (lightConfig.target) {
  97317. if (light.setDirectionToTarget) {
  97318. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  97319. light.setDirectionToTarget(target);
  97320. }
  97321. }
  97322. else if (lightConfig.direction) {
  97323. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  97324. light.direction = direction;
  97325. }
  97326. var shadowGenerator = light.getShadowGenerator();
  97327. if (lightConfig.shadowEnabled && _this._maxShadows) {
  97328. if (!shadowGenerator) {
  97329. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  97330. // TODO blur kernel definition
  97331. }
  97332. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  97333. // add the focues meshes to the shadow list
  97334. var shadownMap = shadowGenerator.getShadowMap();
  97335. if (!shadownMap)
  97336. return;
  97337. var renderList = shadownMap.renderList;
  97338. for (var index = 0; index < focusMeshes.length; index++) {
  97339. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  97340. renderList && renderList.push(focusMeshes[index]);
  97341. }
  97342. }
  97343. }
  97344. else if (shadowGenerator) {
  97345. shadowGenerator.dispose();
  97346. }
  97347. }
  97348. });
  97349. };
  97350. /**
  97351. * configure all models using the configuration.
  97352. * @param modelConfiguration the configuration to use to reconfigure the models
  97353. */
  97354. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  97355. this.models.forEach(function (model) {
  97356. model.updateConfiguration(modelConfiguration);
  97357. });
  97358. };
  97359. /**
  97360. * Dispoe the entire viewer including the scene and the engine
  97361. */
  97362. AbstractViewer.prototype.dispose = function () {
  97363. if (this._isDisposed) {
  97364. return;
  97365. }
  97366. window.removeEventListener('resize', this._resize);
  97367. if (this.sceneOptimizer) {
  97368. this.sceneOptimizer.stop();
  97369. this.sceneOptimizer.dispose();
  97370. }
  97371. if (this.environmentHelper) {
  97372. this.environmentHelper.dispose();
  97373. }
  97374. if (this._configurationLoader) {
  97375. this._configurationLoader.dispose();
  97376. }
  97377. //observers
  97378. this.onEngineInitObservable.clear();
  97379. delete this.onEngineInitObservable;
  97380. this.onInitDoneObservable.clear();
  97381. delete this.onInitDoneObservable;
  97382. this.onLoaderInitObservable.clear();
  97383. delete this.onLoaderInitObservable;
  97384. this.onModelLoadedObservable.clear();
  97385. delete this.onModelLoadedObservable;
  97386. this.onModelLoadErrorObservable.clear();
  97387. delete this.onModelLoadErrorObservable;
  97388. this.onModelLoadProgressObservable.clear();
  97389. delete this.onModelLoadProgressObservable;
  97390. this.onSceneInitObservable.clear();
  97391. delete this.onSceneInitObservable;
  97392. if (this.scene.activeCamera) {
  97393. this.scene.activeCamera.detachControl(this.canvas);
  97394. }
  97395. this.modelLoader.dispose();
  97396. this.models.forEach(function (model) {
  97397. model.dispose();
  97398. });
  97399. this.models.length = 0;
  97400. this.scene.dispose();
  97401. this.engine.dispose();
  97402. this.templateManager.dispose();
  97403. viewerManager_1.viewerManager.removeViewer(this);
  97404. this._isDisposed = true;
  97405. };
  97406. /**
  97407. * This function will execute when the HTML templates finished initializing.
  97408. * It should initialize the engine and continue execution.
  97409. *
  97410. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  97411. */
  97412. AbstractViewer.prototype._onTemplatesLoaded = function () {
  97413. return Promise.resolve(this);
  97414. };
  97415. /**
  97416. * This will force the creation of an engine and a scene.
  97417. * It will also load a model if preconfigured.
  97418. * But first - it will load the extendible onTemplateLoaded()!
  97419. */
  97420. AbstractViewer.prototype._onTemplateLoaded = function () {
  97421. var _this = this;
  97422. return this._onTemplatesLoaded().then(function () {
  97423. var autoLoadModel = _this._configuration.model;
  97424. return _this._initEngine().then(function (engine) {
  97425. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  97426. }).then(function () {
  97427. if (autoLoadModel) {
  97428. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  97429. }
  97430. else {
  97431. return _this.scene || _this._initScene();
  97432. }
  97433. }).then(function (scene) {
  97434. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  97435. }).then(function () {
  97436. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  97437. }).catch(function (e) {
  97438. babylonjs_1.Tools.Warn(e.toString());
  97439. return _this;
  97440. });
  97441. });
  97442. };
  97443. /**
  97444. * Initialize the engine. Retruns a promise in case async calls are needed.
  97445. *
  97446. * @protected
  97447. * @returns {Promise<Engine>}
  97448. * @memberof Viewer
  97449. */
  97450. AbstractViewer.prototype._initEngine = function () {
  97451. // init custom shaders
  97452. this._injectCustomShaders();
  97453. var canvasElement = this.templateManager.getCanvas();
  97454. if (!canvasElement) {
  97455. return Promise.reject('Canvas element not found!');
  97456. }
  97457. var config = this._configuration.engine || {};
  97458. // TDO enable further configuration
  97459. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  97460. // Disable manifest checking
  97461. babylonjs_1.Database.IDBStorageEnabled = false;
  97462. if (!config.disableResize) {
  97463. window.addEventListener('resize', this._resize);
  97464. }
  97465. this.engine.runRenderLoop(this._render);
  97466. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  97467. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  97468. this.engine.setHardwareScalingLevel(scale);
  97469. }
  97470. // set hardware limitations for scene initialization
  97471. this._handleHardwareLimitations();
  97472. return Promise.resolve(this.engine);
  97473. };
  97474. /**
  97475. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  97476. */
  97477. AbstractViewer.prototype._initScene = function () {
  97478. // if the scen exists, dispose it.
  97479. if (this.scene) {
  97480. this.scene.dispose();
  97481. }
  97482. // create a new scene
  97483. this.scene = new babylonjs_1.Scene(this.engine);
  97484. // make sure there is a default camera and light.
  97485. this.scene.createDefaultLight(true);
  97486. if (this._configuration.scene) {
  97487. this._configureScene(this._configuration.scene);
  97488. // Scene optimizer
  97489. if (this._configuration.optimizer) {
  97490. this._configureOptimizer(this._configuration.optimizer);
  97491. }
  97492. }
  97493. return Promise.resolve(this.scene);
  97494. };
  97495. /**
  97496. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  97497. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  97498. *
  97499. * @param modelConfig model configuration to use when loading the model.
  97500. * @param clearScene should the scene be cleared before loading this model
  97501. * @returns a ViewerModel object that is not yet fully loaded.
  97502. */
  97503. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  97504. var _this = this;
  97505. if (clearScene === void 0) { clearScene = true; }
  97506. if (clearScene) {
  97507. this.models.forEach(function (m) { return m.dispose(); });
  97508. this.models.length = 0;
  97509. }
  97510. var model = this.modelLoader.load(modelConfig);
  97511. this.lastUsedLoader = model.loader;
  97512. model.onLoadErrorObservable.add(function (errorObject) {
  97513. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  97514. });
  97515. model.onLoadProgressObservable.add(function (progressEvent) {
  97516. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  97517. });
  97518. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  97519. model.onLoadedObservable.add(function () {
  97520. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  97521. .then(function () {
  97522. _this._configureLights(_this._configuration.lights);
  97523. if (_this._configuration.camera || !_this.scene.activeCamera) {
  97524. _this._configureCamera(_this._configuration.camera || {}, model);
  97525. }
  97526. return _this._initEnvironment(model);
  97527. }).then(function () {
  97528. _this._isLoading = false;
  97529. return model;
  97530. });
  97531. });
  97532. return model;
  97533. };
  97534. /**
  97535. * load a model using the provided configuration
  97536. *
  97537. * @param modelConfig the model configuration or URL to load.
  97538. * @param clearScene Should the scene be cleared before loading the model
  97539. * @returns a Promise the fulfills when the model finished loading successfully.
  97540. */
  97541. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  97542. var _this = this;
  97543. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  97544. if (clearScene === void 0) { clearScene = true; }
  97545. // no model was provided? Do nothing!
  97546. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  97547. if (!modelUrl) {
  97548. return Promise.reject("no model configuration found");
  97549. }
  97550. if (this._isLoading) {
  97551. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  97552. return Promise.reject("another model is curently being loaded.");
  97553. }
  97554. this._isLoading = true;
  97555. if ((typeof modelConfig === 'string')) {
  97556. if (this._configuration.model && typeof this._configuration.model === 'object') {
  97557. this._configuration.model.url = modelConfig;
  97558. }
  97559. }
  97560. else {
  97561. if (this._configuration.model) {
  97562. deepmerge(this._configuration.model, modelConfig);
  97563. }
  97564. else {
  97565. this._configuration.model = modelConfig;
  97566. }
  97567. }
  97568. return Promise.resolve(this.scene).then(function (scene) {
  97569. if (!scene)
  97570. return _this._initScene();
  97571. return scene;
  97572. }).then(function () {
  97573. return new Promise(function (resolve, reject) {
  97574. // at this point, configuration.model is an object, not a string
  97575. return _this.initModel(modelConfig, clearScene);
  97576. });
  97577. });
  97578. };
  97579. /**
  97580. * initialize the environment for a specific model.
  97581. * Per default it will use the viewer'S configuration.
  97582. * @param model the model to use to configure the environment.
  97583. * @returns a Promise that will resolve when the configuration is done.
  97584. */
  97585. AbstractViewer.prototype._initEnvironment = function (model) {
  97586. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  97587. return Promise.resolve(this.scene);
  97588. };
  97589. /**
  97590. * Alters render settings to reduce features based on hardware feature limitations
  97591. * @param enableHDR Allows the viewer to run in HDR mode.
  97592. */
  97593. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  97594. if (enableHDR === void 0) { enableHDR = true; }
  97595. //flip rendering settings switches based on hardware support
  97596. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  97597. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  97598. //shadows are disabled if there's not enough varyings for a single shadow
  97599. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  97600. this._maxShadows = 0;
  97601. }
  97602. else {
  97603. this._maxShadows = 3;
  97604. }
  97605. //can we render to any >= 16-bit targets (required for HDR)
  97606. var caps = this.engine.getCaps();
  97607. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  97608. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  97609. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  97610. if (linearHalfFloatTargets) {
  97611. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  97612. this._shadowGeneratorBias = 0.002;
  97613. }
  97614. else if (linearFloatTargets) {
  97615. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  97616. this._shadowGeneratorBias = 0.001;
  97617. }
  97618. else {
  97619. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  97620. this._shadowGeneratorBias = 0.001;
  97621. }
  97622. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  97623. };
  97624. /**
  97625. * Injects all the spectre shader in the babylon shader store
  97626. */
  97627. AbstractViewer.prototype._injectCustomShaders = function () {
  97628. var customShaders = this._configuration.customShaders;
  97629. // Inject all the spectre shader in the babylon shader store.
  97630. if (!customShaders) {
  97631. return;
  97632. }
  97633. if (customShaders.shaders) {
  97634. Object.keys(customShaders.shaders).forEach(function (key) {
  97635. // typescript considers a callback "unsafe", so... '!'
  97636. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  97637. });
  97638. }
  97639. if (customShaders.includes) {
  97640. Object.keys(customShaders.includes).forEach(function (key) {
  97641. // typescript considers a callback "unsafe", so... '!'
  97642. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  97643. });
  97644. }
  97645. };
  97646. /**
  97647. * This will extend an object with configuration values.
  97648. * What it practically does it take the keys from the configuration and set them on the object.
  97649. * I the configuration is a tree, it will traverse into the tree.
  97650. * @param object the object to extend
  97651. * @param config the configuration object that will extend the object
  97652. */
  97653. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  97654. var _this = this;
  97655. if (!config)
  97656. return;
  97657. Object.keys(config).forEach(function (key) {
  97658. if (key in object && typeof object[key] !== 'function') {
  97659. // if (typeof object[key] === 'function') return;
  97660. // if it is an object, iterate internally until reaching basic types
  97661. if (typeof object[key] === 'object') {
  97662. _this._extendClassWithConfig(object[key], config[key]);
  97663. }
  97664. else {
  97665. if (config[key] !== undefined) {
  97666. object[key] = config[key];
  97667. }
  97668. }
  97669. }
  97670. });
  97671. };
  97672. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  97673. var behavior;
  97674. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  97675. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  97676. // constructing behavior
  97677. switch (type) {
  97678. case 0 /* AUTOROTATION */:
  97679. this.camera.useAutoRotationBehavior = true;
  97680. behavior = this.camera.autoRotationBehavior;
  97681. break;
  97682. case 1 /* BOUNCING */:
  97683. this.camera.useBouncingBehavior = true;
  97684. behavior = this.camera.bouncingBehavior;
  97685. break;
  97686. case 2 /* FRAMING */:
  97687. this.camera.useFramingBehavior = true;
  97688. behavior = this.camera.framingBehavior;
  97689. break;
  97690. default:
  97691. behavior = null;
  97692. break;
  97693. }
  97694. if (behavior) {
  97695. if (typeof behaviorConfig === "object") {
  97696. this._extendClassWithConfig(behavior, behaviorConfig);
  97697. }
  97698. }
  97699. // post attach configuration. Some functionalities require the attached camera.
  97700. switch (type) {
  97701. case 0 /* AUTOROTATION */:
  97702. break;
  97703. case 1 /* BOUNCING */:
  97704. break;
  97705. case 2 /* FRAMING */:
  97706. if (config.zoomOnBoundingInfo) {
  97707. //payload is an array of meshes
  97708. var meshes = payload;
  97709. var bounding = meshes[0].getHierarchyBoundingVectors();
  97710. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  97711. }
  97712. break;
  97713. }
  97714. };
  97715. return AbstractViewer;
  97716. }());
  97717. exports.AbstractViewer = AbstractViewer;
  97718. /***/ }),
  97719. /* 7 */
  97720. /***/ (function(module, exports) {
  97721. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  97722. /***/ }),
  97723. /* 8 */
  97724. /***/ (function(module, exports) {
  97725. 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}}>";
  97726. /***/ }),
  97727. /* 9 */
  97728. /***/ (function(module, exports) {
  97729. 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=="
  97730. /***/ }),
  97731. /* 10 */
  97732. /***/ (function(module, exports) {
  97733. 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>";
  97734. /***/ }),
  97735. /* 11 */
  97736. /***/ (function(module, exports) {
  97737. 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>";
  97738. /***/ }),
  97739. /* 12 */
  97740. /***/ (function(module, exports) {
  97741. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  97742. /***/ }),
  97743. /* 13 */
  97744. /***/ (function(module, exports) {
  97745. module.exports = "Error loading the model";
  97746. /***/ }),
  97747. /* 14 */
  97748. /***/ (function(module, exports, __webpack_require__) {
  97749. "use strict";
  97750. Object.defineProperty(exports, "__esModule", { value: true });
  97751. var babylonjs_1 = __webpack_require__(0);
  97752. var viewerModel_1 = __webpack_require__(15);
  97753. /**
  97754. * An instance of the class is in charge of loading the model correctly.
  97755. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  97756. *
  97757. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  97758. */
  97759. var ModelLoader = /** @class */ (function () {
  97760. /**
  97761. * Create a new Model loader
  97762. * @param _viewer the viewer using this model loader
  97763. */
  97764. function ModelLoader(_viewer) {
  97765. this._viewer = _viewer;
  97766. this._disposed = false;
  97767. this._loaders = [];
  97768. this._loadId = 0;
  97769. }
  97770. /**
  97771. * Load a model using predefined configuration
  97772. * @param modelConfiguration the modelConfiguration to use to load the model
  97773. */
  97774. ModelLoader.prototype.load = function (modelConfiguration) {
  97775. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  97776. if (!modelConfiguration.url) {
  97777. model.state = viewerModel_1.ModelState.ERROR;
  97778. babylonjs_1.Tools.Error("No URL provided");
  97779. return model;
  97780. }
  97781. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  97782. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  97783. var plugin = modelConfiguration.loader;
  97784. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  97785. meshes.forEach(function (mesh) {
  97786. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  97787. });
  97788. model.meshes = meshes;
  97789. model.particleSystems = particleSystems;
  97790. model.skeletons = skeletons;
  97791. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  97792. var animationGroup = animationGroups_1[_i];
  97793. model.addAnimationGroup(animationGroup);
  97794. }
  97795. model.initAnimations();
  97796. model.onLoadedObservable.notifyObserversWithPromise(model);
  97797. }, function (progressEvent) {
  97798. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  97799. }, function (e, m, exception) {
  97800. model.state = viewerModel_1.ModelState.ERROR;
  97801. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  97802. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  97803. }, plugin);
  97804. if (model.loader.name === "gltf") {
  97805. var gltfLoader = model.loader;
  97806. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  97807. }
  97808. model.loadId = this._loadId++;
  97809. this._loaders.push(model.loader);
  97810. return model;
  97811. };
  97812. ModelLoader.prototype.cancelLoad = function (model) {
  97813. var loader = model.loader || this._loaders[model.loadId];
  97814. // ATM only available in the GLTF Loader
  97815. if (loader && loader.name === "gltf") {
  97816. var gltfLoader = loader;
  97817. gltfLoader.dispose();
  97818. model.state = viewerModel_1.ModelState.CANCELED;
  97819. }
  97820. else {
  97821. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  97822. }
  97823. };
  97824. /**
  97825. * dispose the model loader.
  97826. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  97827. */
  97828. ModelLoader.prototype.dispose = function () {
  97829. this._loaders.forEach(function (loader) {
  97830. if (loader.name === "gltf") {
  97831. loader.dispose();
  97832. }
  97833. });
  97834. this._loaders.length = 0;
  97835. this._disposed = true;
  97836. };
  97837. return ModelLoader;
  97838. }());
  97839. exports.ModelLoader = ModelLoader;
  97840. /***/ }),
  97841. /* 15 */
  97842. /***/ (function(module, exports, __webpack_require__) {
  97843. "use strict";
  97844. Object.defineProperty(exports, "__esModule", { value: true });
  97845. var babylonjs_1 = __webpack_require__(0);
  97846. var modelAnimation_1 = __webpack_require__(16);
  97847. var deepmerge = __webpack_require__(2);
  97848. var ModelState;
  97849. (function (ModelState) {
  97850. ModelState[ModelState["INIT"] = 0] = "INIT";
  97851. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  97852. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  97853. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  97854. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  97855. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  97856. /**
  97857. * The viewer model is a container for all assets representing a sngle loaded model.
  97858. */
  97859. var ViewerModel = /** @class */ (function () {
  97860. function ViewerModel(_viewer, modelConfiguration) {
  97861. this._viewer = _viewer;
  97862. /**
  97863. * the list of meshes that are a part of this model
  97864. */
  97865. this.meshes = [];
  97866. /**
  97867. * ParticleSystems connected to this model
  97868. */
  97869. this.particleSystems = [];
  97870. /**
  97871. * Skeletons defined in this model
  97872. */
  97873. this.skeletons = [];
  97874. this.onLoadedObservable = new babylonjs_1.Observable();
  97875. this.onLoadErrorObservable = new babylonjs_1.Observable();
  97876. this.onLoadProgressObservable = new babylonjs_1.Observable();
  97877. this.onAfterConfigure = new babylonjs_1.Observable();
  97878. this.state = ModelState.INIT;
  97879. this._animations = [];
  97880. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  97881. this._modelConfiguration = deepmerge({}, modelConfiguration);
  97882. this._viewer.models.push(this);
  97883. }
  97884. Object.defineProperty(ViewerModel.prototype, "configuration", {
  97885. /**
  97886. * Get the model's configuration
  97887. */
  97888. get: function () {
  97889. return this._modelConfiguration;
  97890. },
  97891. /**
  97892. * (Re-)set the model's entire configuration
  97893. * @param newConfiguration the new configuration to replace the new one
  97894. */
  97895. set: function (newConfiguration) {
  97896. this._modelConfiguration = newConfiguration;
  97897. this._configureModel();
  97898. },
  97899. enumerable: true,
  97900. configurable: true
  97901. });
  97902. /**
  97903. * Update the current configuration with new values.
  97904. * Configuration will not be overwritten, but merged with the new configuration.
  97905. * Priority is to the new configuration
  97906. * @param newConfiguration the configuration to be merged into the current configuration;
  97907. */
  97908. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  97909. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  97910. this._configureModel();
  97911. };
  97912. ViewerModel.prototype.initAnimations = function () {
  97913. var _this = this;
  97914. this._animations.forEach(function (a) {
  97915. a.dispose();
  97916. });
  97917. this._animations.length = 0;
  97918. // check if this is not a gltf loader and init the animations
  97919. if (this.loader.name !== 'gltf') {
  97920. this.skeletons.forEach(function (skeleton, idx) {
  97921. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  97922. skeleton.getAnimatables().forEach(function (a) {
  97923. if (a.animations[0]) {
  97924. ag.addTargetedAnimation(a.animations[0], a);
  97925. }
  97926. });
  97927. _this.addAnimationGroup(ag);
  97928. });
  97929. }
  97930. if (!this._modelConfiguration)
  97931. return;
  97932. if (this._modelConfiguration.animation) {
  97933. if (this._modelConfiguration.animation.playOnce) {
  97934. this._animations.forEach(function (a) {
  97935. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  97936. });
  97937. }
  97938. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  97939. var animationName = this._modelConfiguration.animation.autoStart === true ?
  97940. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  97941. this.playAnimation(animationName);
  97942. }
  97943. }
  97944. };
  97945. /**
  97946. * Add a new animation group to this model.
  97947. * @param animationGroup the new animation group to be added
  97948. */
  97949. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  97950. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  97951. };
  97952. /**
  97953. * Get the ModelAnimation array
  97954. */
  97955. ViewerModel.prototype.getAnimations = function () {
  97956. return this._animations;
  97957. };
  97958. /**
  97959. * Get the animations' names. Using the names you can play a specific animation.
  97960. */
  97961. ViewerModel.prototype.getAnimationNames = function () {
  97962. return this._animations.map(function (a) { return a.name; });
  97963. };
  97964. /**
  97965. * Get an animation by the provided name. Used mainly when playing n animation.
  97966. * @param name the name of the animation to find
  97967. */
  97968. ViewerModel.prototype._getAnimationByName = function (name) {
  97969. // can't use .find, noe available on IE
  97970. var filtered = this._animations.filter(function (a) { return a.name === name; });
  97971. // what the next line means - if two animations have the same name, they will not be returned!
  97972. if (filtered.length === 1) {
  97973. return filtered[0];
  97974. }
  97975. else {
  97976. return null;
  97977. }
  97978. };
  97979. /**
  97980. * Choose an initialized animation using its name and start playing it
  97981. * @param name the name of the animation to play
  97982. * @returns The model aniamtion to be played.
  97983. */
  97984. ViewerModel.prototype.playAnimation = function (name) {
  97985. var animation = this._getAnimationByName(name);
  97986. if (animation) {
  97987. if (this.currentAnimation) {
  97988. this.currentAnimation.stop();
  97989. }
  97990. this.currentAnimation = animation;
  97991. animation.start();
  97992. return animation;
  97993. }
  97994. else {
  97995. throw new Error("animation not found - " + name);
  97996. }
  97997. };
  97998. ViewerModel.prototype._configureModel = function () {
  97999. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  98000. var updateMeshesWithNoParent = function (variable, value, param) {
  98001. meshesWithNoParent.forEach(function (mesh) {
  98002. if (param) {
  98003. mesh[variable][param] = value;
  98004. }
  98005. else {
  98006. mesh[variable] = value;
  98007. }
  98008. });
  98009. };
  98010. var updateXYZ = function (variable, configValues) {
  98011. if (configValues.x !== undefined) {
  98012. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98013. }
  98014. if (configValues.y !== undefined) {
  98015. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98016. }
  98017. if (configValues.z !== undefined) {
  98018. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98019. }
  98020. if (configValues.w !== undefined) {
  98021. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98022. }
  98023. };
  98024. // position?
  98025. if (this._modelConfiguration.position) {
  98026. updateXYZ('position', this._modelConfiguration.position);
  98027. }
  98028. if (this._modelConfiguration.rotation) {
  98029. //quaternion?
  98030. if (this._modelConfiguration.rotation.w) {
  98031. meshesWithNoParent.forEach(function (mesh) {
  98032. if (!mesh.rotationQuaternion) {
  98033. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98034. }
  98035. });
  98036. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98037. }
  98038. else {
  98039. updateXYZ('rotation', this._modelConfiguration.rotation);
  98040. }
  98041. }
  98042. if (this._modelConfiguration.scaling) {
  98043. updateXYZ('scaling', this._modelConfiguration.scaling);
  98044. }
  98045. if (this._modelConfiguration.castShadow) {
  98046. this.meshes.forEach(function (mesh) {
  98047. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98048. });
  98049. }
  98050. if (this._modelConfiguration.normalize) {
  98051. var center = false;
  98052. var unitSize = false;
  98053. var parentIndex = void 0;
  98054. if (this._modelConfiguration.normalize === true) {
  98055. center = true;
  98056. unitSize = true;
  98057. parentIndex = 0;
  98058. }
  98059. else {
  98060. center = !!this._modelConfiguration.normalize.center;
  98061. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98062. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98063. }
  98064. var meshesToNormalize = [];
  98065. if (parentIndex !== undefined) {
  98066. meshesToNormalize.push(this.meshes[parentIndex]);
  98067. }
  98068. else {
  98069. meshesToNormalize = meshesWithNoParent;
  98070. }
  98071. if (unitSize) {
  98072. meshesToNormalize.forEach(function (mesh) {
  98073. mesh.normalizeToUnitCube(true);
  98074. mesh.computeWorldMatrix(true);
  98075. });
  98076. }
  98077. if (center) {
  98078. meshesToNormalize.forEach(function (mesh) {
  98079. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98080. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98081. var halfSizeVec = sizeVec.scale(0.5);
  98082. var center = boundingInfo.min.add(halfSizeVec);
  98083. mesh.position = center.scale(-1);
  98084. // Set on ground.
  98085. mesh.position.y += halfSizeVec.y;
  98086. // Recompute Info.
  98087. mesh.computeWorldMatrix(true);
  98088. });
  98089. }
  98090. }
  98091. this.onAfterConfigure.notifyObservers(this);
  98092. };
  98093. /**
  98094. * Dispose this model, including all of its associated assets.
  98095. */
  98096. ViewerModel.prototype.dispose = function () {
  98097. this.onAfterConfigure.clear();
  98098. this.onLoadedObservable.clear();
  98099. this.onLoadErrorObservable.clear();
  98100. this.onLoadProgressObservable.clear();
  98101. if (this.loader && this.loader.name === "gltf") {
  98102. this.loader.dispose();
  98103. }
  98104. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98105. this.particleSystems.length = 0;
  98106. this.skeletons.forEach(function (s) { return s.dispose(); });
  98107. this.skeletons.length = 0;
  98108. this._animations.forEach(function (ag) { return ag.dispose(); });
  98109. this._animations.length = 0;
  98110. this.meshes.forEach(function (m) { return m.dispose(); });
  98111. this.meshes.length = 0;
  98112. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  98113. };
  98114. return ViewerModel;
  98115. }());
  98116. exports.ViewerModel = ViewerModel;
  98117. /***/ }),
  98118. /* 16 */
  98119. /***/ (function(module, exports, __webpack_require__) {
  98120. "use strict";
  98121. Object.defineProperty(exports, "__esModule", { value: true });
  98122. /**
  98123. * Animation play mode enum - is the animation looping or playing once
  98124. */
  98125. var AnimationPlayMode;
  98126. (function (AnimationPlayMode) {
  98127. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  98128. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  98129. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  98130. /**
  98131. * An enum representing the current state of an animation object
  98132. */
  98133. var AnimationState;
  98134. (function (AnimationState) {
  98135. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  98136. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  98137. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  98138. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  98139. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  98140. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  98141. /**
  98142. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  98143. * native GroupAnimation class.
  98144. */
  98145. var GroupModelAnimation = /** @class */ (function () {
  98146. /**
  98147. * Create a new GroupModelAnimation object using an AnimationGroup object
  98148. * @param _animationGroup The aniamtion group to base the class on
  98149. */
  98150. function GroupModelAnimation(_animationGroup) {
  98151. var _this = this;
  98152. this._animationGroup = _animationGroup;
  98153. this._state = AnimationState.INIT;
  98154. this._playMode = AnimationPlayMode.LOOP;
  98155. this._animationGroup.onAnimationEndObservable.add(function () {
  98156. _this.stop();
  98157. _this._state = AnimationState.ENDED;
  98158. });
  98159. }
  98160. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  98161. /**
  98162. * Get the animation's name
  98163. */
  98164. get: function () {
  98165. return this._animationGroup.name;
  98166. },
  98167. enumerable: true,
  98168. configurable: true
  98169. });
  98170. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  98171. /**
  98172. * Get the current animation's state
  98173. */
  98174. get: function () {
  98175. return this._state;
  98176. },
  98177. enumerable: true,
  98178. configurable: true
  98179. });
  98180. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  98181. /**
  98182. * Gets the speed ratio to use for all animations
  98183. */
  98184. get: function () {
  98185. return this._animationGroup.speedRatio;
  98186. },
  98187. /**
  98188. * Sets the speed ratio to use for all animations
  98189. */
  98190. set: function (value) {
  98191. this._animationGroup.speedRatio = value;
  98192. },
  98193. enumerable: true,
  98194. configurable: true
  98195. });
  98196. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  98197. /**
  98198. * Get the max numbers of frame available in the animation group
  98199. *
  98200. * In correlation to an arry, this would be ".length"
  98201. */
  98202. get: function () {
  98203. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  98204. var keys = ta.animation.getKeys();
  98205. return keys[keys.length - 1].frame;
  98206. });
  98207. return Math.max.apply(null, animationFrames);
  98208. },
  98209. enumerable: true,
  98210. configurable: true
  98211. });
  98212. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  98213. /**
  98214. * Get the current frame playing right now.
  98215. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  98216. *
  98217. * In correlation to an array, this would be the current index
  98218. */
  98219. get: function () {
  98220. // get the first currentFrame found
  98221. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98222. var animatable = this._animationGroup.animatables[i];
  98223. var animations = animatable.getAnimations();
  98224. if (!animations || !animations.length) {
  98225. continue;
  98226. }
  98227. for (var idx = 0; idx < animations.length; ++idx) {
  98228. if (animations[idx].currentFrame) {
  98229. return animations[idx].currentFrame;
  98230. }
  98231. }
  98232. }
  98233. return 0;
  98234. },
  98235. enumerable: true,
  98236. configurable: true
  98237. });
  98238. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  98239. /**
  98240. * Get the FPS value of this animation
  98241. */
  98242. get: function () {
  98243. // get the first currentFrame found
  98244. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98245. var animatable = this._animationGroup.animatables[i];
  98246. var animations = animatable.getAnimations();
  98247. if (!animations || !animations.length) {
  98248. continue;
  98249. }
  98250. for (var idx = 0; idx < animations.length; ++idx) {
  98251. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  98252. return animations[idx].animation.framePerSecond;
  98253. }
  98254. }
  98255. }
  98256. return 0;
  98257. },
  98258. enumerable: true,
  98259. configurable: true
  98260. });
  98261. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  98262. /**
  98263. * What is the animation'S play mode (looping or played once)
  98264. */
  98265. get: function () {
  98266. return this._playMode;
  98267. },
  98268. /**
  98269. * Set the play mode.
  98270. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  98271. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  98272. */
  98273. set: function (value) {
  98274. if (value === this._playMode) {
  98275. return;
  98276. }
  98277. this._playMode = value;
  98278. if (this.state === AnimationState.PLAYING) {
  98279. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  98280. }
  98281. else {
  98282. this._animationGroup.reset();
  98283. this._state = AnimationState.INIT;
  98284. }
  98285. },
  98286. enumerable: true,
  98287. configurable: true
  98288. });
  98289. /**
  98290. * Reset the animation group
  98291. */
  98292. GroupModelAnimation.prototype.reset = function () {
  98293. this._animationGroup.reset();
  98294. };
  98295. /**
  98296. * Restart the animation group
  98297. */
  98298. GroupModelAnimation.prototype.restart = function () {
  98299. this._animationGroup.restart();
  98300. };
  98301. /**
  98302. *
  98303. * @param frameNumber Go to a specific frame in the animation
  98304. */
  98305. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  98306. // this._animationGroup.goToFrame(frameNumber);
  98307. this._animationGroup['_animatables'].forEach(function (a) {
  98308. a.goToFrame(frameNumber);
  98309. });
  98310. };
  98311. /**
  98312. * Start playing the animation.
  98313. */
  98314. GroupModelAnimation.prototype.start = function () {
  98315. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  98316. if (this._animationGroup.isStarted) {
  98317. this._state = AnimationState.PLAYING;
  98318. }
  98319. };
  98320. /**
  98321. * Pause the animation
  98322. */
  98323. GroupModelAnimation.prototype.pause = function () {
  98324. this._animationGroup.pause();
  98325. this._state = AnimationState.PAUSED;
  98326. };
  98327. /**
  98328. * Stop the animation.
  98329. * This will fail silently if the animation group is already stopped.
  98330. */
  98331. GroupModelAnimation.prototype.stop = function () {
  98332. this._animationGroup.stop();
  98333. if (!this._animationGroup.isStarted) {
  98334. this._state = AnimationState.STOPPED;
  98335. }
  98336. };
  98337. /**
  98338. * Dispose this animation object.
  98339. */
  98340. GroupModelAnimation.prototype.dispose = function () {
  98341. this._animationGroup.dispose();
  98342. };
  98343. return GroupModelAnimation;
  98344. }());
  98345. exports.GroupModelAnimation = GroupModelAnimation;
  98346. /***/ }),
  98347. /* 17 */
  98348. /***/ (function(module, exports, __webpack_require__) {
  98349. module.exports = __webpack_require__(18);
  98350. /***/ }),
  98351. /* 18 */
  98352. /***/ (function(module, exports, __webpack_require__) {
  98353. "use strict";
  98354. Object.defineProperty(exports, "__esModule", { value: true });
  98355. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98356. var mappers_1 = __webpack_require__(1);
  98357. exports.mapperManager = mappers_1.mapperManager;
  98358. var viewerManager_1 = __webpack_require__(4);
  98359. exports.viewerManager = viewerManager_1.viewerManager;
  98360. var defaultViewer_1 = __webpack_require__(5);
  98361. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98362. var viewer_1 = __webpack_require__(6);
  98363. exports.AbstractViewer = viewer_1.AbstractViewer;
  98364. var modelLoader_1 = __webpack_require__(14);
  98365. exports.ModelLoader = modelLoader_1.ModelLoader;
  98366. var viewerModel_1 = __webpack_require__(15);
  98367. exports.ViewerModel = viewerModel_1.ViewerModel;
  98368. exports.ModelState = viewerModel_1.ModelState;
  98369. var modelAnimation_1 = __webpack_require__(16);
  98370. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  98371. exports.AnimationState = modelAnimation_1.AnimationState;
  98372. /**
  98373. * BabylonJS Viewer
  98374. *
  98375. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98376. */
  98377. var babylonjs_1 = __webpack_require__(0);
  98378. // load needed modules.
  98379. __webpack_require__(34);
  98380. __webpack_require__(35);
  98381. var initializer_1 = __webpack_require__(36);
  98382. exports.InitTags = initializer_1.InitTags;
  98383. // promise polyfill, if needed!
  98384. babylonjs_1.PromisePolyfill.Apply();
  98385. exports.disableInit = false;
  98386. document.addEventListener("DOMContentLoaded", init);
  98387. function init(event) {
  98388. document.removeEventListener("DOMContentLoaded", init);
  98389. if (exports.disableInit)
  98390. return;
  98391. initializer_1.InitTags();
  98392. }
  98393. /**
  98394. * Dispose all viewers currently registered
  98395. */
  98396. function disposeAll() {
  98397. viewerManager_1.viewerManager.dispose();
  98398. mappers_1.mapperManager.dispose();
  98399. }
  98400. exports.disposeAll = disposeAll;
  98401. /***/ }),
  98402. /* 19 */
  98403. /***/ (function(module, exports) {
  98404. var g;
  98405. // This works in non-strict mode
  98406. g = (function() {
  98407. return this;
  98408. })();
  98409. try {
  98410. // This works if eval is allowed (see CSP)
  98411. g = g || Function("return this")() || (1,eval)("this");
  98412. } catch(e) {
  98413. // This works if the window reference is available
  98414. if(typeof window === "object")
  98415. g = window;
  98416. }
  98417. // g can still be undefined, but nothing to do about it...
  98418. // We return undefined, instead of nothing here, so it's
  98419. // easier to handle this case. if(!global) { ...}
  98420. module.exports = g;
  98421. /***/ }),
  98422. /* 20 */
  98423. /***/ (function(module, exports) {
  98424. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98425. module.exports = CANNON;
  98426. /***/ }),
  98427. /* 21 */
  98428. /***/ (function(module, exports) {
  98429. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98430. module.exports = OIMO;
  98431. /***/ }),
  98432. /* 22 */
  98433. /***/ (function(module, exports) {
  98434. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98435. module.exports = earcut;
  98436. /***/ }),
  98437. /* 23 */
  98438. /***/ (function(module, exports, __webpack_require__) {
  98439. "use strict";
  98440. Object.defineProperty(exports, "__esModule", { value: true });
  98441. var babylonjs_1 = __webpack_require__(0);
  98442. var helper_1 = __webpack_require__(3);
  98443. /**
  98444. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  98445. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  98446. */
  98447. var TemplateManager = /** @class */ (function () {
  98448. function TemplateManager(containerElement) {
  98449. this.containerElement = containerElement;
  98450. this.templates = {};
  98451. this.onTemplateInit = new babylonjs_1.Observable();
  98452. this.onTemplateLoaded = new babylonjs_1.Observable();
  98453. this.onTemplateStateChange = new babylonjs_1.Observable();
  98454. this.onAllLoaded = new babylonjs_1.Observable();
  98455. this.onEventTriggered = new babylonjs_1.Observable();
  98456. this.eventManager = new eventManager_1.EventManager(this);
  98457. }
  98458. /**
  98459. * Initialize the template(s) for the viewer. Called bay the Viewer class
  98460. * @param templates the templates to be used to initialize the main template
  98461. */
  98462. TemplateManager.prototype.initTemplate = function (templates) {
  98463. var _this = this;
  98464. var internalInit = function (dependencyMap, name, parentTemplate) {
  98465. //init template
  98466. var template = _this.templates[name];
  98467. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  98468. return internalInit(dependencyMap[childName], childName, template);
  98469. });
  98470. // register the observers
  98471. //template.onLoaded.add(() => {
  98472. var addToParent = function () {
  98473. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  98474. template.appendTo(containingElement);
  98475. _this._checkLoadedState();
  98476. };
  98477. if (parentTemplate && !parentTemplate.parent) {
  98478. parentTemplate.onAppended.add(function () {
  98479. addToParent();
  98480. });
  98481. }
  98482. else {
  98483. addToParent();
  98484. }
  98485. //});
  98486. return template;
  98487. };
  98488. //build the html tree
  98489. return this._buildHTMLTree(templates).then(function (htmlTree) {
  98490. if (_this.templates['main']) {
  98491. internalInit(htmlTree, 'main');
  98492. }
  98493. else {
  98494. _this._checkLoadedState();
  98495. }
  98496. return;
  98497. });
  98498. };
  98499. /**
  98500. *
  98501. * This function will create a simple map with child-dependencies of the template html tree.
  98502. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  98503. * It is expected that the main template will be called main!
  98504. *
  98505. * @param templates
  98506. */
  98507. TemplateManager.prototype._buildHTMLTree = function (templates) {
  98508. var _this = this;
  98509. var promises = Object.keys(templates).map(function (name) {
  98510. // if the template was overridden
  98511. if (!templates[name])
  98512. return Promise.resolve(false);
  98513. // else - we have a template, let's do our job!
  98514. var template = new Template(name, templates[name]);
  98515. template.onLoaded.add(function () {
  98516. _this.onTemplateLoaded.notifyObservers(template);
  98517. });
  98518. template.onStateChange.add(function () {
  98519. _this.onTemplateStateChange.notifyObservers(template);
  98520. });
  98521. _this.onTemplateInit.notifyObservers(template);
  98522. // make sure the global onEventTriggered is called as well
  98523. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  98524. _this.templates[name] = template;
  98525. return template.initPromise;
  98526. });
  98527. return Promise.all(promises).then(function () {
  98528. var templateStructure = {};
  98529. // now iterate through all templates and check for children:
  98530. var buildTree = function (parentObject, name) {
  98531. _this.templates[name].isInHtmlTree = true;
  98532. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  98533. childNodes.forEach(function (element) {
  98534. parentObject[element] = {};
  98535. buildTree(parentObject[element], element);
  98536. });
  98537. };
  98538. if (_this.templates['main']) {
  98539. buildTree(templateStructure, "main");
  98540. }
  98541. return templateStructure;
  98542. });
  98543. };
  98544. /**
  98545. * Get the canvas in the template tree.
  98546. * There must be one and only one canvas inthe template.
  98547. */
  98548. TemplateManager.prototype.getCanvas = function () {
  98549. return this.containerElement.querySelector('canvas');
  98550. };
  98551. /**
  98552. * Get a specific template from the template tree
  98553. * @param name the name of the template to load
  98554. */
  98555. TemplateManager.prototype.getTemplate = function (name) {
  98556. return this.templates[name];
  98557. };
  98558. TemplateManager.prototype._checkLoadedState = function () {
  98559. var _this = this;
  98560. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  98561. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  98562. });
  98563. if (done) {
  98564. this.onAllLoaded.notifyObservers(this);
  98565. }
  98566. };
  98567. /**
  98568. * Dispose the template manager
  98569. */
  98570. TemplateManager.prototype.dispose = function () {
  98571. var _this = this;
  98572. // dispose all templates
  98573. Object.keys(this.templates).forEach(function (template) {
  98574. _this.templates[template].dispose();
  98575. });
  98576. this.templates = {};
  98577. this.eventManager.dispose();
  98578. this.onTemplateInit.clear();
  98579. this.onAllLoaded.clear();
  98580. this.onEventTriggered.clear();
  98581. this.onTemplateLoaded.clear();
  98582. this.onTemplateStateChange.clear();
  98583. };
  98584. return TemplateManager;
  98585. }());
  98586. exports.TemplateManager = TemplateManager;
  98587. var Handlebars = __webpack_require__(24);
  98588. var eventManager_1 = __webpack_require__(25);
  98589. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  98590. Handlebars.registerHelper('eachInMap', function (map, block) {
  98591. var out = '';
  98592. Object.keys(map).map(function (prop) {
  98593. var data = map[prop];
  98594. if (typeof data === 'object') {
  98595. data.id = data.id || prop;
  98596. out += block.fn(data);
  98597. }
  98598. else {
  98599. out += block.fn({ id: prop, value: data });
  98600. }
  98601. });
  98602. return out;
  98603. });
  98604. /**
  98605. * This class represents a single template in the viewer's template tree.
  98606. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  98607. * A template is injected using the template manager in the correct position.
  98608. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  98609. *
  98610. * For further information please refer to the documentation page, https://doc.babylonjs.com
  98611. */
  98612. var Template = /** @class */ (function () {
  98613. function Template(name, _configuration) {
  98614. var _this = this;
  98615. this.name = name;
  98616. this._configuration = _configuration;
  98617. this.onLoaded = new babylonjs_1.Observable();
  98618. this.onAppended = new babylonjs_1.Observable();
  98619. this.onStateChange = new babylonjs_1.Observable();
  98620. this.onEventTriggered = new babylonjs_1.Observable();
  98621. this.loadRequests = [];
  98622. this.isLoaded = false;
  98623. this.isShown = false;
  98624. this.isInHtmlTree = false;
  98625. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  98626. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  98627. if (htmlTemplate) {
  98628. _this._htmlTemplate = htmlTemplate;
  98629. var compiledTemplate = Handlebars.compile(htmlTemplate);
  98630. var config = _this._configuration.params || {};
  98631. var rawHtml = compiledTemplate(config);
  98632. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  98633. _this.isLoaded = true;
  98634. _this.isShown = true;
  98635. _this.onLoaded.notifyObservers(_this);
  98636. }
  98637. return _this;
  98638. });
  98639. }
  98640. /**
  98641. * Some templates have parameters (like background color for example).
  98642. * The parameters are provided to Handlebars which in turn generates the template.
  98643. * This function will update the template with the new parameters
  98644. *
  98645. * @param params the new template parameters
  98646. */
  98647. Template.prototype.updateParams = function (params) {
  98648. this._configuration.params = params;
  98649. // update the template
  98650. if (this.isLoaded) {
  98651. this.dispose();
  98652. }
  98653. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  98654. var config = this._configuration.params || {};
  98655. var rawHtml = compiledTemplate(config);
  98656. this._fragment = document.createRange().createContextualFragment(rawHtml);
  98657. if (this.parent) {
  98658. this.appendTo(this.parent, true);
  98659. }
  98660. };
  98661. Object.defineProperty(Template.prototype, "configuration", {
  98662. /**
  98663. * Get the template'S configuration
  98664. */
  98665. get: function () {
  98666. return this._configuration;
  98667. },
  98668. enumerable: true,
  98669. configurable: true
  98670. });
  98671. /**
  98672. * A template can be a parent element for other templates or HTML elements.
  98673. * This function will deliver all child HTML elements of this template.
  98674. */
  98675. Template.prototype.getChildElements = function () {
  98676. var childrenArray = [];
  98677. //Edge and IE don't support frage,ent.children
  98678. var children = this._fragment.children;
  98679. if (!children) {
  98680. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  98681. children = this._fragment.querySelectorAll('*');
  98682. }
  98683. for (var i = 0; i < children.length; ++i) {
  98684. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  98685. }
  98686. return childrenArray;
  98687. };
  98688. /**
  98689. * Appending the template to a parent HTML element.
  98690. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  98691. * @param parent the parent to which the template is added
  98692. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  98693. */
  98694. Template.prototype.appendTo = function (parent, forceRemove) {
  98695. var _this = this;
  98696. if (this.parent) {
  98697. if (forceRemove) {
  98698. this.parent.removeChild(this._fragment);
  98699. }
  98700. else {
  98701. return;
  98702. }
  98703. }
  98704. this.parent = parent;
  98705. if (this._configuration.id) {
  98706. this.parent.id = this._configuration.id;
  98707. }
  98708. this._fragment = this.parent.appendChild(this._fragment);
  98709. // appended only one frame after.
  98710. setTimeout(function () {
  98711. _this._registerEvents();
  98712. _this.onAppended.notifyObservers(_this);
  98713. });
  98714. };
  98715. /**
  98716. * Show the template using the provided visibilityFunction, or natively using display: flex.
  98717. * The provided function returns a promise that should be fullfilled when the element is shown.
  98718. * Since it is a promise async operations are more than possible.
  98719. * See the default viewer for an opacity example.
  98720. * @param visibilityFunction The function to execute to show the template.
  98721. */
  98722. Template.prototype.show = function (visibilityFunction) {
  98723. var _this = this;
  98724. if (this._isHiding)
  98725. return Promise.resolve(this);
  98726. return Promise.resolve().then(function () {
  98727. _this._isShowing = true;
  98728. if (visibilityFunction) {
  98729. return visibilityFunction(_this);
  98730. }
  98731. else {
  98732. // flex? box? should this be configurable easier than the visibilityFunction?
  98733. _this.parent.style.display = 'flex';
  98734. return _this;
  98735. }
  98736. }).then(function () {
  98737. _this.isShown = true;
  98738. _this._isShowing = false;
  98739. _this.onStateChange.notifyObservers(_this);
  98740. return _this;
  98741. });
  98742. };
  98743. /**
  98744. * Hide the template using the provided visibilityFunction, or natively using display: none.
  98745. * The provided function returns a promise that should be fullfilled when the element is hidden.
  98746. * Since it is a promise async operations are more than possible.
  98747. * See the default viewer for an opacity example.
  98748. * @param visibilityFunction The function to execute to show the template.
  98749. */
  98750. Template.prototype.hide = function (visibilityFunction) {
  98751. var _this = this;
  98752. if (this._isShowing)
  98753. return Promise.resolve(this);
  98754. return Promise.resolve().then(function () {
  98755. _this._isHiding = true;
  98756. if (visibilityFunction) {
  98757. return visibilityFunction(_this);
  98758. }
  98759. else {
  98760. // flex? box? should this be configurable easier than the visibilityFunction?
  98761. _this.parent.style.display = 'hide';
  98762. return _this;
  98763. }
  98764. }).then(function () {
  98765. _this.isShown = false;
  98766. _this._isHiding = false;
  98767. _this.onStateChange.notifyObservers(_this);
  98768. return _this;
  98769. });
  98770. };
  98771. /**
  98772. * Dispose this template
  98773. */
  98774. Template.prototype.dispose = function () {
  98775. this.onAppended.clear();
  98776. this.onEventTriggered.clear();
  98777. this.onLoaded.clear();
  98778. this.onStateChange.clear();
  98779. this.isLoaded = false;
  98780. // remove from parent
  98781. try {
  98782. this.parent.removeChild(this._fragment);
  98783. }
  98784. catch (e) {
  98785. //noop
  98786. }
  98787. this.loadRequests.forEach(function (request) {
  98788. request.abort();
  98789. });
  98790. if (this._registeredEvents) {
  98791. this._registeredEvents.forEach(function (evt) {
  98792. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  98793. });
  98794. }
  98795. delete this._fragment;
  98796. };
  98797. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  98798. var _this = this;
  98799. if (!templateConfig) {
  98800. return Promise.reject('No templateConfig provided');
  98801. }
  98802. else if (templateConfig.html !== undefined) {
  98803. return Promise.resolve(templateConfig.html);
  98804. }
  98805. else {
  98806. var location_1 = this._getTemplateLocation(templateConfig);
  98807. if (helper_1.isUrl(location_1)) {
  98808. return new Promise(function (resolve, reject) {
  98809. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  98810. resolve(data);
  98811. }, undefined, undefined, false, function (request, error) {
  98812. reject(error);
  98813. });
  98814. _this.loadRequests.push(fileRequest);
  98815. });
  98816. }
  98817. else {
  98818. location_1 = location_1.replace('#', '');
  98819. var element = document.getElementById(location_1);
  98820. if (element) {
  98821. return Promise.resolve(element.innerHTML);
  98822. }
  98823. else {
  98824. return Promise.reject('Template ID not found');
  98825. }
  98826. }
  98827. }
  98828. };
  98829. Template.prototype._registerEvents = function () {
  98830. var _this = this;
  98831. this._registeredEvents = this._registeredEvents || [];
  98832. if (this._registeredEvents.length) {
  98833. // first remove the registered events
  98834. this._registeredEvents.forEach(function (evt) {
  98835. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  98836. });
  98837. }
  98838. if (this._configuration.events) {
  98839. var _loop_1 = function (eventName) {
  98840. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  98841. var functionToFire_1 = function (selector, event) {
  98842. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  98843. };
  98844. // if boolean, set the parent as the event listener
  98845. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  98846. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  98847. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  98848. this_1._registeredEvents.push({
  98849. htmlElement: this_1.parent,
  98850. eventName: eventName,
  98851. function: binding
  98852. });
  98853. }
  98854. else if (typeof this_1._configuration.events[eventName] === 'object') {
  98855. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  98856. // strict null checl is working incorrectly, must override:
  98857. var event_1 = this_1._configuration.events[eventName] || {};
  98858. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  98859. if (selector && selector.indexOf('#') !== 0) {
  98860. selector = '#' + selector;
  98861. }
  98862. var htmlElement = _this.parent.querySelector(selector);
  98863. if (htmlElement) {
  98864. var binding = functionToFire_1.bind(_this, selector);
  98865. htmlElement.addEventListener(eventName, binding, false);
  98866. _this._registeredEvents.push({
  98867. htmlElement: htmlElement,
  98868. eventName: eventName,
  98869. function: binding
  98870. });
  98871. }
  98872. });
  98873. }
  98874. }
  98875. };
  98876. var this_1 = this;
  98877. for (var eventName in this._configuration.events) {
  98878. _loop_1(eventName);
  98879. }
  98880. }
  98881. };
  98882. Template.prototype._getTemplateLocation = function (templateConfig) {
  98883. if (!templateConfig || typeof templateConfig === 'string') {
  98884. return templateConfig;
  98885. }
  98886. else {
  98887. return templateConfig.location;
  98888. }
  98889. };
  98890. return Template;
  98891. }());
  98892. exports.Template = Template;
  98893. /***/ }),
  98894. /* 24 */
  98895. /***/ (function(module, exports, __webpack_require__) {
  98896. /**!
  98897. @license
  98898. handlebars v4.0.11
  98899. Copyright (C) 2011-2017 by Yehuda Katz
  98900. Permission is hereby granted, free of charge, to any person obtaining a copy
  98901. of this software and associated documentation files (the "Software"), to deal
  98902. in the Software without restriction, including without limitation the rights
  98903. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  98904. copies of the Software, and to permit persons to whom the Software is
  98905. furnished to do so, subject to the following conditions:
  98906. The above copyright notice and this permission notice shall be included in
  98907. all copies or substantial portions of the Software.
  98908. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  98909. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  98910. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  98911. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  98912. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  98913. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  98914. THE SOFTWARE.
  98915. */
  98916. !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],
  98917. 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){
  98918. 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"]}])});
  98919. /***/ }),
  98920. /* 25 */
  98921. /***/ (function(module, exports, __webpack_require__) {
  98922. "use strict";
  98923. Object.defineProperty(exports, "__esModule", { value: true });
  98924. /**
  98925. * The EventManager is in charge of registering user interctions with the viewer.
  98926. * It is used in the TemplateManager
  98927. */
  98928. var EventManager = /** @class */ (function () {
  98929. function EventManager(_templateManager) {
  98930. var _this = this;
  98931. this._templateManager = _templateManager;
  98932. this._callbacksContainer = {};
  98933. this._templateManager.onEventTriggered.add(function (eventData) {
  98934. _this._eventTriggered(eventData);
  98935. });
  98936. }
  98937. /**
  98938. * Register a new callback to a specific template.
  98939. * The best example for the usage can be found in the DefaultViewer
  98940. *
  98941. * @param templateName the templateName to register the event to
  98942. * @param callback The callback to be executed
  98943. * @param eventType the type of event to register
  98944. * @param selector an optional selector. if not defined the parent object in the template will be selected
  98945. */
  98946. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  98947. if (!this._callbacksContainer[templateName]) {
  98948. this._callbacksContainer[templateName] = [];
  98949. }
  98950. this._callbacksContainer[templateName].push({
  98951. eventType: eventType,
  98952. callback: callback
  98953. });
  98954. };
  98955. /**
  98956. * This will remove a registered event from the defined template.
  98957. * Each one of the variables apart from the template name are optional, but one must be provided.
  98958. *
  98959. * @param templateName the templateName
  98960. * @param callback the callback to remove (optional)
  98961. * @param eventType the event type to remove (optional)
  98962. * @param selector the selector from which to remove the event (optional)
  98963. */
  98964. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  98965. var callbackDefs = this._callbacksContainer[templateName] || [];
  98966. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  98967. };
  98968. EventManager.prototype._eventTriggered = function (data) {
  98969. var templateName = data.template.name;
  98970. var eventType = data.event.type;
  98971. var selector = data.selector;
  98972. var callbackDefs = this._callbacksContainer[templateName] || [];
  98973. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  98974. callbackDef.callback(data);
  98975. });
  98976. };
  98977. /**
  98978. * Dispose the event manager
  98979. */
  98980. EventManager.prototype.dispose = function () {
  98981. this._callbacksContainer = {};
  98982. };
  98983. return EventManager;
  98984. }());
  98985. exports.EventManager = EventManager;
  98986. /***/ }),
  98987. /* 26 */
  98988. /***/ (function(module, exports, __webpack_require__) {
  98989. "use strict";
  98990. Object.defineProperty(exports, "__esModule", { value: true });
  98991. var mappers_1 = __webpack_require__(1);
  98992. var types_1 = __webpack_require__(27);
  98993. var deepmerge = __webpack_require__(2);
  98994. var babylonjs_1 = __webpack_require__(0);
  98995. /**
  98996. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  98997. * parse the object and return a conform ViewerConfiguration.
  98998. * It is a private member of the scene.
  98999. */
  99000. var ConfigurationLoader = /** @class */ (function () {
  99001. function ConfigurationLoader(_enableCache) {
  99002. if (_enableCache === void 0) { _enableCache = false; }
  99003. this._enableCache = _enableCache;
  99004. this._configurationCache = {};
  99005. this._loadRequests = [];
  99006. }
  99007. /**
  99008. * load a configuration object that is defined in the initial configuration provided.
  99009. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  99010. *
  99011. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  99012. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  99013. * @returns A promise that delivers the extended viewer configuration, when done.
  99014. */
  99015. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  99016. var _this = this;
  99017. if (initConfig === void 0) { initConfig = {}; }
  99018. var loadedConfig = deepmerge({}, initConfig);
  99019. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  99020. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  99021. if (loadedConfig.configuration) {
  99022. var mapperType_1 = "json";
  99023. return Promise.resolve().then(function () {
  99024. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  99025. // a file to load
  99026. var url = '';
  99027. if (typeof loadedConfig.configuration === "string") {
  99028. url = loadedConfig.configuration;
  99029. }
  99030. // if configuration is an object
  99031. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  99032. url = loadedConfig.configuration.url;
  99033. var type = loadedConfig.configuration.mapper;
  99034. // empty string?
  99035. if (!type) {
  99036. // load mapper type from filename / url
  99037. type = loadedConfig.configuration.url.split('.').pop();
  99038. }
  99039. mapperType_1 = type || mapperType_1;
  99040. }
  99041. return _this._loadFile(url);
  99042. }
  99043. else {
  99044. if (typeof loadedConfig.configuration === "object") {
  99045. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  99046. return loadedConfig.configuration.payload || {};
  99047. }
  99048. return {};
  99049. }
  99050. }).then(function (data) {
  99051. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  99052. var parsed = mapper.map(data);
  99053. var merged = deepmerge(loadedConfig, parsed);
  99054. if (callback)
  99055. callback(merged);
  99056. return merged;
  99057. });
  99058. }
  99059. else {
  99060. if (callback)
  99061. callback(loadedConfig);
  99062. return Promise.resolve(loadedConfig);
  99063. }
  99064. };
  99065. /**
  99066. * Dispose the configuration loader. This will cancel file requests, if active.
  99067. */
  99068. ConfigurationLoader.prototype.dispose = function () {
  99069. this._loadRequests.forEach(function (request) {
  99070. request.abort();
  99071. });
  99072. this._loadRequests.length = 0;
  99073. };
  99074. ConfigurationLoader.prototype._loadFile = function (url) {
  99075. var _this = this;
  99076. var cacheReference = this._configurationCache;
  99077. if (this._enableCache && cacheReference[url]) {
  99078. return Promise.resolve(cacheReference[url]);
  99079. }
  99080. return new Promise(function (resolve, reject) {
  99081. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  99082. var idx = _this._loadRequests.indexOf(fileRequest);
  99083. if (idx !== -1)
  99084. _this._loadRequests.splice(idx, 1);
  99085. if (_this._enableCache)
  99086. cacheReference[url] = result;
  99087. resolve(result);
  99088. }, undefined, undefined, false, function (request, error) {
  99089. var idx = _this._loadRequests.indexOf(fileRequest);
  99090. if (idx !== -1)
  99091. _this._loadRequests.splice(idx, 1);
  99092. reject(error);
  99093. });
  99094. _this._loadRequests.push(fileRequest);
  99095. });
  99096. };
  99097. return ConfigurationLoader;
  99098. }());
  99099. exports.ConfigurationLoader = ConfigurationLoader;
  99100. /***/ }),
  99101. /* 27 */
  99102. /***/ (function(module, exports, __webpack_require__) {
  99103. "use strict";
  99104. Object.defineProperty(exports, "__esModule", { value: true });
  99105. var minimal_1 = __webpack_require__(28);
  99106. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  99107. var default_1 = __webpack_require__(29);
  99108. exports.defaultConfiguration = default_1.defaultConfiguration;
  99109. var getConfigurationType = function (type) {
  99110. switch (type) {
  99111. case 'default':
  99112. return default_1.defaultConfiguration;
  99113. case 'minimal':
  99114. return minimal_1.minimalConfiguration;
  99115. case 'none':
  99116. return {};
  99117. default:
  99118. return default_1.defaultConfiguration;
  99119. }
  99120. };
  99121. exports.getConfigurationType = getConfigurationType;
  99122. /***/ }),
  99123. /* 28 */
  99124. /***/ (function(module, exports, __webpack_require__) {
  99125. "use strict";
  99126. Object.defineProperty(exports, "__esModule", { value: true });
  99127. exports.minimalConfiguration = {
  99128. version: "0.1",
  99129. templates: {
  99130. main: {
  99131. html: __webpack_require__(7)
  99132. },
  99133. loadingScreen: {
  99134. html: __webpack_require__(8),
  99135. params: {
  99136. backgroundColor: "#000000",
  99137. loadingImage: __webpack_require__(9) //"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"
  99138. }
  99139. },
  99140. viewer: {
  99141. html: __webpack_require__(10),
  99142. },
  99143. overlay: {
  99144. html: __webpack_require__(11),
  99145. params: {
  99146. closeImage: __webpack_require__(12),
  99147. closeText: 'Close'
  99148. }
  99149. },
  99150. error: {
  99151. html: __webpack_require__(13)
  99152. }
  99153. },
  99154. engine: {
  99155. antialiasing: true
  99156. }
  99157. };
  99158. /***/ }),
  99159. /* 29 */
  99160. /***/ (function(module, exports, __webpack_require__) {
  99161. "use strict";
  99162. Object.defineProperty(exports, "__esModule", { value: true });
  99163. exports.defaultConfiguration = {
  99164. version: "3.2.0-alpha4",
  99165. templates: {
  99166. main: {
  99167. html: __webpack_require__(7)
  99168. },
  99169. loadingScreen: {
  99170. html: __webpack_require__(8),
  99171. params: {
  99172. backgroundColor: "#000000",
  99173. loadingImage: __webpack_require__(9)
  99174. }
  99175. },
  99176. viewer: {
  99177. html: __webpack_require__(10),
  99178. events: {
  99179. pointerout: true,
  99180. pointerdown: true,
  99181. pointerup: true
  99182. }
  99183. },
  99184. navBar: {
  99185. html: __webpack_require__(30),
  99186. params: {
  99187. buttons: {
  99188. /*"help-button": {
  99189. altText: "Help",
  99190. image: require('../../../assets/img/help-circle.png')
  99191. },*/
  99192. "fullscreen-button": {
  99193. altText: "Fullscreen",
  99194. image: __webpack_require__(31)
  99195. }
  99196. },
  99197. visibilityTimeout: 2000
  99198. },
  99199. events: {
  99200. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  99201. pointerover: true
  99202. }
  99203. },
  99204. overlay: {
  99205. html: __webpack_require__(11),
  99206. params: {
  99207. closeImage: __webpack_require__(12),
  99208. closeText: 'Close'
  99209. }
  99210. },
  99211. help: {
  99212. html: __webpack_require__(32)
  99213. },
  99214. share: {
  99215. html: __webpack_require__(33)
  99216. },
  99217. error: {
  99218. html: __webpack_require__(13)
  99219. }
  99220. },
  99221. camera: {
  99222. behaviors: {
  99223. autoRotate: 0,
  99224. framing: {
  99225. type: 2,
  99226. zoomOnBoundingInfo: true,
  99227. zoomStopsAnimation: false
  99228. }
  99229. }
  99230. },
  99231. /*lights: {
  99232. "default": {
  99233. type: 1,
  99234. shadowEnabled: true,
  99235. direction: { x: -0.2, y: -0.8, z: 0 },
  99236. position: { x: 10, y: 10, z: 0 },
  99237. intensity: 4.5,
  99238. shadowConfig: {
  99239. useBlurExponentialShadowMap: true,
  99240. useKernelBlur: true,
  99241. blurKernel: 64,
  99242. blurScale: 4
  99243. }
  99244. }
  99245. },*/
  99246. skybox: {
  99247. /*cubeTexture: {
  99248. url: 'https://playground.babylonjs.com/textures/environment.dds',
  99249. gammaSpace: false
  99250. },*/
  99251. pbr: true,
  99252. blur: 0.7,
  99253. infiniteDIstance: false,
  99254. },
  99255. ground: true,
  99256. engine: {
  99257. antialiasing: true
  99258. },
  99259. scene: {
  99260. imageProcessingConfiguration: {
  99261. exposure: 1.4,
  99262. contrast: 1.66,
  99263. toneMappingEnabled: true
  99264. }
  99265. }
  99266. };
  99267. /***/ }),
  99268. /* 30 */
  99269. /***/ (function(module, exports) {
  99270. 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>";
  99271. /***/ }),
  99272. /* 31 */
  99273. /***/ (function(module, exports) {
  99274. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  99275. /***/ }),
  99276. /* 32 */
  99277. /***/ (function(module, exports) {
  99278. module.exports = "HELP";
  99279. /***/ }),
  99280. /* 33 */
  99281. /***/ (function(module, exports) {
  99282. module.exports = "SHARE";
  99283. /***/ }),
  99284. /* 34 */
  99285. /***/ (function(module, exports, __webpack_require__) {
  99286. (function universalModuleDefinition(root, factory) {
  99287. var amdDependencies = [];
  99288. var BABYLON = root.BABYLON || this.BABYLON;
  99289. if(true) {
  99290. BABYLON = BABYLON || __webpack_require__(0);
  99291. module.exports = factory(BABYLON);
  99292. } else if(typeof define === 'function' && define.amd) {
  99293. amdDependencies.push("babylonjs");
  99294. define("babylonjs-loaders", amdDependencies, factory);
  99295. } else if(typeof exports === 'object') {
  99296. BABYLON = BABYLON || require("babylonjs");
  99297. exports["babylonjs-loaders"] = factory(BABYLON);
  99298. } else {
  99299. root["BABYLON"] = factory(BABYLON);
  99300. }
  99301. })(this, function(BABYLON) {
  99302. BABYLON = BABYLON || this.BABYLON;
  99303. 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};
  99304. 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)}}();
  99305. var BABYLON;
  99306. (function (BABYLON) {
  99307. var STLFileLoader = /** @class */ (function () {
  99308. function STLFileLoader() {
  99309. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  99310. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  99311. 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;
  99312. 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;
  99313. this.name = "stl";
  99314. // force data to come in as an ArrayBuffer
  99315. // we'll convert to string if it looks like it's an ASCII .stl
  99316. this.extensions = {
  99317. ".stl": { isBinary: true },
  99318. };
  99319. }
  99320. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99321. var matches;
  99322. if (this.isBinary(data)) {
  99323. // binary .stl
  99324. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  99325. this.parseBinary(babylonMesh, data);
  99326. if (meshes) {
  99327. meshes.push(babylonMesh);
  99328. }
  99329. return true;
  99330. }
  99331. // ASCII .stl
  99332. // convert to string
  99333. var array_buffer = new Uint8Array(data);
  99334. var str = '';
  99335. for (var i = 0; i < data.byteLength; i++) {
  99336. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  99337. }
  99338. data = str;
  99339. while (matches = this.solidPattern.exec(data)) {
  99340. var meshName = matches[1];
  99341. var meshNameFromEnd = matches[3];
  99342. if (meshName != meshNameFromEnd) {
  99343. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  99344. return false;
  99345. }
  99346. // check meshesNames
  99347. if (meshesNames && meshName) {
  99348. if (meshesNames instanceof Array) {
  99349. if (!meshesNames.indexOf(meshName)) {
  99350. continue;
  99351. }
  99352. }
  99353. else {
  99354. if (meshName !== meshesNames) {
  99355. continue;
  99356. }
  99357. }
  99358. }
  99359. // stl mesh name can be empty as well
  99360. meshName = meshName || "stlmesh";
  99361. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  99362. this.parseASCII(babylonMesh, matches[2]);
  99363. if (meshes) {
  99364. meshes.push(babylonMesh);
  99365. }
  99366. }
  99367. return true;
  99368. };
  99369. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  99370. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  99371. if (result) {
  99372. scene.createDefaultCameraOrLight();
  99373. }
  99374. return result;
  99375. };
  99376. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99377. var container = new BABYLON.AssetContainer(scene);
  99378. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99379. container.removeAllFromScene();
  99380. return container;
  99381. };
  99382. STLFileLoader.prototype.isBinary = function (data) {
  99383. // check if file size is correct for binary stl
  99384. var faceSize, nFaces, reader;
  99385. reader = new DataView(data);
  99386. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  99387. nFaces = reader.getUint32(80, true);
  99388. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  99389. return true;
  99390. }
  99391. // check characters higher than ASCII to confirm binary
  99392. var fileLength = reader.byteLength;
  99393. for (var index = 0; index < fileLength; index++) {
  99394. if (reader.getUint8(index) > 127) {
  99395. return true;
  99396. }
  99397. }
  99398. return false;
  99399. };
  99400. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  99401. var reader = new DataView(data);
  99402. var faces = reader.getUint32(80, true);
  99403. var dataOffset = 84;
  99404. var faceLength = 12 * 4 + 2;
  99405. var offset = 0;
  99406. var positions = new Float32Array(faces * 3 * 3);
  99407. var normals = new Float32Array(faces * 3 * 3);
  99408. var indices = new Uint32Array(faces * 3);
  99409. var indicesCount = 0;
  99410. for (var face = 0; face < faces; face++) {
  99411. var start = dataOffset + face * faceLength;
  99412. var normalX = reader.getFloat32(start, true);
  99413. var normalY = reader.getFloat32(start + 4, true);
  99414. var normalZ = reader.getFloat32(start + 8, true);
  99415. for (var i = 1; i <= 3; i++) {
  99416. var vertexstart = start + i * 12;
  99417. // ordering is intentional to match ascii import
  99418. positions[offset] = reader.getFloat32(vertexstart, true);
  99419. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  99420. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  99421. normals[offset] = normalX;
  99422. normals[offset + 2] = normalY;
  99423. normals[offset + 1] = normalZ;
  99424. offset += 3;
  99425. }
  99426. indices[indicesCount] = indicesCount++;
  99427. indices[indicesCount] = indicesCount++;
  99428. indices[indicesCount] = indicesCount++;
  99429. }
  99430. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99431. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99432. mesh.setIndices(indices);
  99433. mesh.computeWorldMatrix(true);
  99434. };
  99435. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  99436. var positions = [];
  99437. var normals = [];
  99438. var indices = [];
  99439. var indicesCount = 0;
  99440. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  99441. var matches;
  99442. while (matches = this.facetsPattern.exec(solidData)) {
  99443. var facet = matches[1];
  99444. //one normal per face
  99445. var normalMatches = this.normalPattern.exec(facet);
  99446. this.normalPattern.lastIndex = 0;
  99447. if (!normalMatches) {
  99448. continue;
  99449. }
  99450. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  99451. var vertexMatch;
  99452. while (vertexMatch = this.vertexPattern.exec(facet)) {
  99453. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  99454. normals.push(normal[0], normal[1], normal[2]);
  99455. }
  99456. indices.push(indicesCount++, indicesCount++, indicesCount++);
  99457. this.vertexPattern.lastIndex = 0;
  99458. }
  99459. this.facetsPattern.lastIndex = 0;
  99460. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99461. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99462. mesh.setIndices(indices);
  99463. mesh.computeWorldMatrix(true);
  99464. };
  99465. return STLFileLoader;
  99466. }());
  99467. BABYLON.STLFileLoader = STLFileLoader;
  99468. if (BABYLON.SceneLoader) {
  99469. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  99470. }
  99471. })(BABYLON || (BABYLON = {}));
  99472. //# sourceMappingURL=babylon.stlFileLoader.js.map
  99473. var BABYLON;
  99474. (function (BABYLON) {
  99475. /**
  99476. * Class reading and parsing the MTL file bundled with the obj file.
  99477. */
  99478. var MTLFileLoader = /** @class */ (function () {
  99479. function MTLFileLoader() {
  99480. // All material loaded from the mtl will be set here
  99481. this.materials = [];
  99482. }
  99483. /**
  99484. * This function will read the mtl file and create each material described inside
  99485. * This function could be improve by adding :
  99486. * -some component missing (Ni, Tf...)
  99487. * -including the specific options available
  99488. *
  99489. * @param scene
  99490. * @param data
  99491. * @param rootUrl
  99492. */
  99493. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  99494. if (data instanceof ArrayBuffer) {
  99495. return;
  99496. }
  99497. //Split the lines from the file
  99498. var lines = data.split('\n');
  99499. //Space char
  99500. var delimiter_pattern = /\s+/;
  99501. //Array with RGB colors
  99502. var color;
  99503. //New material
  99504. var material = null;
  99505. //Look at each line
  99506. for (var i = 0; i < lines.length; i++) {
  99507. var line = lines[i].trim();
  99508. // Blank line or comment
  99509. if (line.length === 0 || line.charAt(0) === '#') {
  99510. continue;
  99511. }
  99512. //Get the first parameter (keyword)
  99513. var pos = line.indexOf(' ');
  99514. var key = (pos >= 0) ? line.substring(0, pos) : line;
  99515. key = key.toLowerCase();
  99516. //Get the data following the key
  99517. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  99518. //This mtl keyword will create the new material
  99519. if (key === "newmtl") {
  99520. //Check if it is the first material.
  99521. // Materials specifications are described after this keyword.
  99522. if (material) {
  99523. //Add the previous material in the material array.
  99524. this.materials.push(material);
  99525. }
  99526. //Create a new material.
  99527. // value is the name of the material read in the mtl file
  99528. material = new BABYLON.StandardMaterial(value, scene);
  99529. }
  99530. else if (key === "kd" && material) {
  99531. // Diffuse color (color under white light) using RGB values
  99532. //value = "r g b"
  99533. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99534. //color = [r,g,b]
  99535. //Set tghe color into the material
  99536. material.diffuseColor = BABYLON.Color3.FromArray(color);
  99537. }
  99538. else if (key === "ka" && material) {
  99539. // Ambient color (color under shadow) using RGB values
  99540. //value = "r g b"
  99541. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99542. //color = [r,g,b]
  99543. //Set tghe color into the material
  99544. material.ambientColor = BABYLON.Color3.FromArray(color);
  99545. }
  99546. else if (key === "ks" && material) {
  99547. // Specular color (color when light is reflected from shiny surface) using RGB values
  99548. //value = "r g b"
  99549. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99550. //color = [r,g,b]
  99551. //Set the color into the material
  99552. material.specularColor = BABYLON.Color3.FromArray(color);
  99553. }
  99554. else if (key === "ke" && material) {
  99555. // Emissive color using RGB values
  99556. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99557. material.emissiveColor = BABYLON.Color3.FromArray(color);
  99558. }
  99559. else if (key === "ns" && material) {
  99560. //value = "Integer"
  99561. material.specularPower = parseFloat(value);
  99562. }
  99563. else if (key === "d" && material) {
  99564. //d is dissolve for current material. It mean alpha for BABYLON
  99565. material.alpha = parseFloat(value);
  99566. //Texture
  99567. //This part can be improved by adding the possible options of texture
  99568. }
  99569. else if (key === "map_ka" && material) {
  99570. // ambient texture map with a loaded image
  99571. //We must first get the folder of the image
  99572. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99573. }
  99574. else if (key === "map_kd" && material) {
  99575. // Diffuse texture map with a loaded image
  99576. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99577. }
  99578. else if (key === "map_ks" && material) {
  99579. // Specular texture map with a loaded image
  99580. //We must first get the folder of the image
  99581. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99582. }
  99583. else if (key === "map_ns") {
  99584. //Specular
  99585. //Specular highlight component
  99586. //We must first get the folder of the image
  99587. //
  99588. //Not supported by BABYLON
  99589. //
  99590. // continue;
  99591. }
  99592. else if (key === "map_bump" && material) {
  99593. //The bump texture
  99594. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99595. }
  99596. else if (key === "map_d" && material) {
  99597. // The dissolve of the material
  99598. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99599. //Options for illumination
  99600. }
  99601. else if (key === "illum") {
  99602. //Illumination
  99603. if (value === "0") {
  99604. //That mean Kd == Kd
  99605. }
  99606. else if (value === "1") {
  99607. //Color on and Ambient on
  99608. }
  99609. else if (value === "2") {
  99610. //Highlight on
  99611. }
  99612. else if (value === "3") {
  99613. //Reflection on and Ray trace on
  99614. }
  99615. else if (value === "4") {
  99616. //Transparency: Glass on, Reflection: Ray trace on
  99617. }
  99618. else if (value === "5") {
  99619. //Reflection: Fresnel on and Ray trace on
  99620. }
  99621. else if (value === "6") {
  99622. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  99623. }
  99624. else if (value === "7") {
  99625. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  99626. }
  99627. else if (value === "8") {
  99628. //Reflection on and Ray trace off
  99629. }
  99630. else if (value === "9") {
  99631. //Transparency: Glass on, Reflection: Ray trace off
  99632. }
  99633. else if (value === "10") {
  99634. //Casts shadows onto invisible surfaces
  99635. }
  99636. }
  99637. else {
  99638. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  99639. }
  99640. }
  99641. //At the end of the file, add the last material
  99642. if (material) {
  99643. this.materials.push(material);
  99644. }
  99645. };
  99646. /**
  99647. * Gets the texture for the material.
  99648. *
  99649. * If the material is imported from input file,
  99650. * We sanitize the url to ensure it takes the textre from aside the material.
  99651. *
  99652. * @param rootUrl The root url to load from
  99653. * @param value The value stored in the mtl
  99654. * @return The Texture
  99655. */
  99656. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  99657. if (!value) {
  99658. return null;
  99659. }
  99660. var url = rootUrl;
  99661. // Load from input file.
  99662. if (rootUrl === "file:") {
  99663. var lastDelimiter = value.lastIndexOf("\\");
  99664. if (lastDelimiter === -1) {
  99665. lastDelimiter = value.lastIndexOf("/");
  99666. }
  99667. if (lastDelimiter > -1) {
  99668. url += value.substr(lastDelimiter + 1);
  99669. }
  99670. else {
  99671. url += value;
  99672. }
  99673. }
  99674. // Not from input file.
  99675. else {
  99676. url += value;
  99677. }
  99678. return new BABYLON.Texture(url, scene);
  99679. };
  99680. return MTLFileLoader;
  99681. }());
  99682. BABYLON.MTLFileLoader = MTLFileLoader;
  99683. var OBJFileLoader = /** @class */ (function () {
  99684. function OBJFileLoader() {
  99685. this.name = "obj";
  99686. this.extensions = ".obj";
  99687. this.obj = /^o/;
  99688. this.group = /^g/;
  99689. this.mtllib = /^mtllib /;
  99690. this.usemtl = /^usemtl /;
  99691. this.smooth = /^s /;
  99692. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99693. // vn float float float
  99694. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99695. // vt float float
  99696. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99697. // f vertex vertex vertex ...
  99698. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  99699. // f vertex/uvs vertex/uvs vertex/uvs ...
  99700. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99701. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  99702. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99703. // f vertex//normal vertex//normal vertex//normal ...
  99704. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  99705. }
  99706. /**
  99707. * Calls synchronously the MTL file attached to this obj.
  99708. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  99709. * Without this function materials are not displayed in the first frame (but displayed after).
  99710. * In consequence it is impossible to get material information in your HTML file
  99711. *
  99712. * @param url The URL of the MTL file
  99713. * @param rootUrl
  99714. * @param onSuccess Callback function to be called when the MTL file is loaded
  99715. * @private
  99716. */
  99717. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  99718. //The complete path to the mtl file
  99719. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  99720. // Loads through the babylon tools to allow fileInput search.
  99721. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  99722. };
  99723. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99724. //get the meshes from OBJ file
  99725. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  99726. //Push meshes from OBJ file into the variable mesh of this function
  99727. if (meshes) {
  99728. loadedMeshes.forEach(function (mesh) {
  99729. meshes.push(mesh);
  99730. });
  99731. }
  99732. return true;
  99733. };
  99734. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  99735. //Get the 3D model
  99736. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  99737. };
  99738. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99739. var container = new BABYLON.AssetContainer(scene);
  99740. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99741. container.removeAllFromScene();
  99742. return container;
  99743. };
  99744. /**
  99745. * Read the OBJ file and create an Array of meshes.
  99746. * Each mesh contains all information given by the OBJ and the MTL file.
  99747. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  99748. *
  99749. * @param meshesNames
  99750. * @param scene BABYLON.Scene The scene where are displayed the data
  99751. * @param data String The content of the obj file
  99752. * @param rootUrl String The path to the folder
  99753. * @returns Array<AbstractMesh>
  99754. * @private
  99755. */
  99756. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  99757. var positions = []; //values for the positions of vertices
  99758. var normals = []; //Values for the normals
  99759. var uvs = []; //Values for the textures
  99760. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  99761. var handledMesh; //The current mesh of meshes array
  99762. var indicesForBabylon = []; //The list of indices for VertexData
  99763. var wrappedPositionForBabylon = []; //The list of position in vectors
  99764. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  99765. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  99766. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  99767. var curPositionInIndices = 0;
  99768. var hasMeshes = false; //Meshes are defined in the file
  99769. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  99770. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  99771. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  99772. var triangles = []; //Indices from new triangles coming from polygons
  99773. var materialNameFromObj = ""; //The name of the current material
  99774. var fileToLoad = ""; //The name of the mtlFile to load
  99775. var materialsFromMTLFile = new MTLFileLoader();
  99776. var objMeshName = ""; //The name of the current obj mesh
  99777. var increment = 1; //Id for meshes created by the multimaterial
  99778. var isFirstMaterial = true;
  99779. /**
  99780. * Search for obj in the given array.
  99781. * This function is called to check if a couple of data already exists in an array.
  99782. *
  99783. * If found, returns the index of the founded tuple index. Returns -1 if not found
  99784. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  99785. * @param obj Array<number>
  99786. * @returns {boolean}
  99787. */
  99788. var isInArray = function (arr, obj) {
  99789. if (!arr[obj[0]])
  99790. arr[obj[0]] = { normals: [], idx: [] };
  99791. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  99792. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  99793. };
  99794. var isInArrayUV = function (arr, obj) {
  99795. if (!arr[obj[0]])
  99796. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  99797. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  99798. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  99799. return arr[obj[0]].idx[idx];
  99800. }
  99801. return -1;
  99802. };
  99803. /**
  99804. * This function set the data for each triangle.
  99805. * Data are position, normals and uvs
  99806. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  99807. * If the tuple already exist, add only their indice
  99808. *
  99809. * @param indicePositionFromObj Integer The index in positions array
  99810. * @param indiceUvsFromObj Integer The index in uvs array
  99811. * @param indiceNormalFromObj Integer The index in normals array
  99812. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  99813. * @param textureVectorFromOBJ Vector3 The value of uvs
  99814. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  99815. */
  99816. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  99817. //Check if this tuple already exists in the list of tuples
  99818. var _index;
  99819. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  99820. _index = isInArrayUV(tuplePosNorm, [
  99821. indicePositionFromObj,
  99822. indiceNormalFromObj,
  99823. indiceUvsFromObj
  99824. ]);
  99825. }
  99826. else {
  99827. _index = isInArray(tuplePosNorm, [
  99828. indicePositionFromObj,
  99829. indiceNormalFromObj
  99830. ]);
  99831. }
  99832. //If it not exists
  99833. if (_index == -1) {
  99834. //Add an new indice.
  99835. //The array of indices is only an array with his length equal to the number of triangles - 1.
  99836. //We add vertices data in this order
  99837. indicesForBabylon.push(wrappedPositionForBabylon.length);
  99838. //Push the position of vertice for Babylon
  99839. //Each element is a BABYLON.Vector3(x,y,z)
  99840. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  99841. //Push the uvs for Babylon
  99842. //Each element is a BABYLON.Vector3(u,v)
  99843. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  99844. //Push the normals for Babylon
  99845. //Each element is a BABYLON.Vector3(x,y,z)
  99846. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  99847. //Add the tuple in the comparison list
  99848. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  99849. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  99850. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  99851. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  99852. }
  99853. else {
  99854. //The tuple already exists
  99855. //Add the index of the already existing tuple
  99856. //At this index we can get the value of position, normal and uvs of vertex
  99857. indicesForBabylon.push(_index);
  99858. }
  99859. };
  99860. /**
  99861. * Transform BABYLON.Vector() object onto 3 digits in an array
  99862. */
  99863. var unwrapData = function () {
  99864. //Every array has the same length
  99865. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  99866. //Push the x, y, z values of each element in the unwrapped array
  99867. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  99868. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  99869. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  99870. }
  99871. // Reset arrays for the next new meshes
  99872. wrappedPositionForBabylon = [];
  99873. wrappedNormalsForBabylon = [];
  99874. wrappedUvsForBabylon = [];
  99875. tuplePosNorm = [];
  99876. curPositionInIndices = 0;
  99877. };
  99878. /**
  99879. * Create triangles from polygons by recursion
  99880. * The best to understand how it works is to draw it in the same time you get the recursion.
  99881. * It is important to notice that a triangle is a polygon
  99882. * We get 4 patterns of face defined in OBJ File :
  99883. * facePattern1 = ["1","2","3","4","5","6"]
  99884. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  99885. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  99886. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  99887. * Each pattern is divided by the same method
  99888. * @param face Array[String] The indices of elements
  99889. * @param v Integer The variable to increment
  99890. */
  99891. var getTriangles = function (face, v) {
  99892. //Work for each element of the array
  99893. if (v + 1 < face.length) {
  99894. //Add on the triangle variable the indexes to obtain triangles
  99895. triangles.push(face[0], face[v], face[v + 1]);
  99896. //Incrementation for recursion
  99897. v += 1;
  99898. //Recursion
  99899. getTriangles(face, v);
  99900. }
  99901. //Result obtained after 2 iterations:
  99902. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  99903. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  99904. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  99905. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  99906. };
  99907. /**
  99908. * Create triangles and push the data for each polygon for the pattern 1
  99909. * In this pattern we get vertice positions
  99910. * @param face
  99911. * @param v
  99912. */
  99913. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  99914. //Get the indices of triangles for each polygon
  99915. getTriangles(face, v);
  99916. //For each element in the triangles array.
  99917. //This var could contains 1 to an infinity of triangles
  99918. for (var k = 0; k < triangles.length; k++) {
  99919. // Set position indice
  99920. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  99921. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  99922. positions[indicePositionFromObj], //Get the vectors data
  99923. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  99924. );
  99925. }
  99926. //Reset variable for the next line
  99927. triangles = [];
  99928. };
  99929. /**
  99930. * Create triangles and push the data for each polygon for the pattern 2
  99931. * In this pattern we get vertice positions and uvsu
  99932. * @param face
  99933. * @param v
  99934. */
  99935. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  99936. //Get the indices of triangles for each polygon
  99937. getTriangles(face, v);
  99938. for (var k = 0; k < triangles.length; k++) {
  99939. //triangle[k] = "1/1"
  99940. //Split the data for getting position and uv
  99941. var point = triangles[k].split("/"); // ["1", "1"]
  99942. //Set position indice
  99943. var indicePositionFromObj = parseInt(point[0]) - 1;
  99944. //Set uv indice
  99945. var indiceUvsFromObj = parseInt(point[1]) - 1;
  99946. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  99947. positions[indicePositionFromObj], //Get the values for each element
  99948. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  99949. );
  99950. }
  99951. //Reset variable for the next line
  99952. triangles = [];
  99953. };
  99954. /**
  99955. * Create triangles and push the data for each polygon for the pattern 3
  99956. * In this pattern we get vertice positions, uvs and normals
  99957. * @param face
  99958. * @param v
  99959. */
  99960. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  99961. //Get the indices of triangles for each polygon
  99962. getTriangles(face, v);
  99963. for (var k = 0; k < triangles.length; k++) {
  99964. //triangle[k] = "1/1/1"
  99965. //Split the data for getting position, uv, and normals
  99966. var point = triangles[k].split("/"); // ["1", "1", "1"]
  99967. // Set position indice
  99968. var indicePositionFromObj = parseInt(point[0]) - 1;
  99969. // Set uv indice
  99970. var indiceUvsFromObj = parseInt(point[1]) - 1;
  99971. // Set normal indice
  99972. var indiceNormalFromObj = parseInt(point[2]) - 1;
  99973. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  99974. );
  99975. }
  99976. //Reset variable for the next line
  99977. triangles = [];
  99978. };
  99979. /**
  99980. * Create triangles and push the data for each polygon for the pattern 4
  99981. * In this pattern we get vertice positions and normals
  99982. * @param face
  99983. * @param v
  99984. */
  99985. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  99986. getTriangles(face, v);
  99987. for (var k = 0; k < triangles.length; k++) {
  99988. //triangle[k] = "1//1"
  99989. //Split the data for getting position and normals
  99990. var point = triangles[k].split("//"); // ["1", "1"]
  99991. // We check indices, and normals
  99992. var indicePositionFromObj = parseInt(point[0]) - 1;
  99993. var indiceNormalFromObj = parseInt(point[1]) - 1;
  99994. setData(indicePositionFromObj, 1, //Default value for uv
  99995. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  99996. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  99997. }
  99998. //Reset variable for the next line
  99999. triangles = [];
  100000. };
  100001. var addPreviousObjMesh = function () {
  100002. //Check if it is not the first mesh. Otherwise we don't have data.
  100003. if (meshesFromObj.length > 0) {
  100004. //Get the previous mesh for applying the data about the faces
  100005. //=> in obj file, faces definition append after the name of the mesh
  100006. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100007. //Set the data into Array for the mesh
  100008. unwrapData();
  100009. // Reverse tab. Otherwise face are displayed in the wrong sens
  100010. indicesForBabylon.reverse();
  100011. //Set the information for the mesh
  100012. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  100013. handledMesh.indices = indicesForBabylon.slice();
  100014. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  100015. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  100016. handledMesh.uvs = unwrappedUVForBabylon.slice();
  100017. //Reset the array for the next mesh
  100018. indicesForBabylon = [];
  100019. unwrappedPositionsForBabylon = [];
  100020. unwrappedNormalsForBabylon = [];
  100021. unwrappedUVForBabylon = [];
  100022. }
  100023. };
  100024. //Main function
  100025. //Split the file into lines
  100026. var lines = data.split('\n');
  100027. //Look at each line
  100028. for (var i = 0; i < lines.length; i++) {
  100029. var line = lines[i].trim();
  100030. var result;
  100031. //Comment or newLine
  100032. if (line.length === 0 || line.charAt(0) === '#') {
  100033. continue;
  100034. //Get information about one position possible for the vertices
  100035. }
  100036. else if ((result = this.vertexPattern.exec(line)) !== null) {
  100037. //Create a Vector3 with the position x, y, z
  100038. //Value of result:
  100039. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100040. //Add the Vector in the list of positions
  100041. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100042. }
  100043. else if ((result = this.normalPattern.exec(line)) !== null) {
  100044. //Create a Vector3 with the normals x, y, z
  100045. //Value of result
  100046. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100047. //Add the Vector in the list of normals
  100048. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100049. }
  100050. else if ((result = this.uvPattern.exec(line)) !== null) {
  100051. //Create a Vector2 with the normals u, v
  100052. //Value of result
  100053. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  100054. //Add the Vector in the list of uvs
  100055. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  100056. //Identify patterns of faces
  100057. //Face could be defined in different type of pattern
  100058. }
  100059. else if ((result = this.facePattern3.exec(line)) !== null) {
  100060. //Value of result:
  100061. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  100062. //Set the data for this face
  100063. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  100064. 1);
  100065. }
  100066. else if ((result = this.facePattern4.exec(line)) !== null) {
  100067. //Value of result:
  100068. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  100069. //Set the data for this face
  100070. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  100071. 1);
  100072. }
  100073. else if ((result = this.facePattern2.exec(line)) !== null) {
  100074. //Value of result:
  100075. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  100076. //Set the data for this face
  100077. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  100078. 1);
  100079. }
  100080. else if ((result = this.facePattern1.exec(line)) !== null) {
  100081. //Value of result
  100082. //["f 1 2 3", "1 2 3"...]
  100083. //Set the data for this face
  100084. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  100085. 1);
  100086. //Define a mesh or an object
  100087. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  100088. }
  100089. else if (this.group.test(line) || this.obj.test(line)) {
  100090. //Create a new mesh corresponding to the name of the group.
  100091. //Definition of the mesh
  100092. var objMesh =
  100093. //Set the name of the current obj mesh
  100094. {
  100095. name: line.substring(2).trim(),
  100096. indices: undefined,
  100097. positions: undefined,
  100098. normals: undefined,
  100099. uvs: undefined,
  100100. materialName: ""
  100101. };
  100102. addPreviousObjMesh();
  100103. //Push the last mesh created with only the name
  100104. meshesFromObj.push(objMesh);
  100105. //Set this variable to indicate that now meshesFromObj has objects defined inside
  100106. hasMeshes = true;
  100107. isFirstMaterial = true;
  100108. increment = 1;
  100109. //Keyword for applying a material
  100110. }
  100111. else if (this.usemtl.test(line)) {
  100112. //Get the name of the material
  100113. materialNameFromObj = line.substring(7).trim();
  100114. //If this new material is in the same mesh
  100115. if (!isFirstMaterial) {
  100116. //Set the data for the previous mesh
  100117. addPreviousObjMesh();
  100118. //Create a new mesh
  100119. var objMesh =
  100120. //Set the name of the current obj mesh
  100121. {
  100122. name: objMeshName + "_mm" + increment.toString(),
  100123. indices: undefined,
  100124. positions: undefined,
  100125. normals: undefined,
  100126. uvs: undefined,
  100127. materialName: materialNameFromObj
  100128. };
  100129. increment++;
  100130. //If meshes are already defined
  100131. meshesFromObj.push(objMesh);
  100132. }
  100133. //Set the material name if the previous line define a mesh
  100134. if (hasMeshes && isFirstMaterial) {
  100135. //Set the material name to the previous mesh (1 material per mesh)
  100136. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  100137. isFirstMaterial = false;
  100138. }
  100139. //Keyword for loading the mtl file
  100140. }
  100141. else if (this.mtllib.test(line)) {
  100142. //Get the name of mtl file
  100143. fileToLoad = line.substring(7).trim();
  100144. //Apply smoothing
  100145. }
  100146. else if (this.smooth.test(line)) {
  100147. // smooth shading => apply smoothing
  100148. //Toda y I don't know it work with babylon and with obj.
  100149. //With the obj file an integer is set
  100150. }
  100151. else {
  100152. //If there is another possibility
  100153. console.log("Unhandled expression at line : " + line);
  100154. }
  100155. }
  100156. //At the end of the file, add the last mesh into the meshesFromObj array
  100157. if (hasMeshes) {
  100158. //Set the data for the last mesh
  100159. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100160. //Reverse indices for displaying faces in the good sens
  100161. indicesForBabylon.reverse();
  100162. //Get the good array
  100163. unwrapData();
  100164. //Set array
  100165. handledMesh.indices = indicesForBabylon;
  100166. handledMesh.positions = unwrappedPositionsForBabylon;
  100167. handledMesh.normals = unwrappedNormalsForBabylon;
  100168. handledMesh.uvs = unwrappedUVForBabylon;
  100169. }
  100170. //If any o or g keyword found, create a mesj with a random id
  100171. if (!hasMeshes) {
  100172. // reverse tab of indices
  100173. indicesForBabylon.reverse();
  100174. //Get positions normals uvs
  100175. unwrapData();
  100176. //Set data for one mesh
  100177. meshesFromObj.push({
  100178. name: BABYLON.Geometry.RandomId(),
  100179. indices: indicesForBabylon,
  100180. positions: unwrappedPositionsForBabylon,
  100181. normals: unwrappedNormalsForBabylon,
  100182. uvs: unwrappedUVForBabylon,
  100183. materialName: materialNameFromObj
  100184. });
  100185. }
  100186. //Create a BABYLON.Mesh list
  100187. var babylonMeshesArray = []; //The mesh for babylon
  100188. var materialToUse = new Array();
  100189. //Set data for each mesh
  100190. for (var j = 0; j < meshesFromObj.length; j++) {
  100191. //check meshesNames (stlFileLoader)
  100192. if (meshesNames && meshesFromObj[j].name) {
  100193. if (meshesNames instanceof Array) {
  100194. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  100195. continue;
  100196. }
  100197. }
  100198. else {
  100199. if (meshesFromObj[j].name !== meshesNames) {
  100200. continue;
  100201. }
  100202. }
  100203. }
  100204. //Get the current mesh
  100205. //Set the data with VertexBuffer for each mesh
  100206. handledMesh = meshesFromObj[j];
  100207. //Create a BABYLON.Mesh with the name of the obj mesh
  100208. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  100209. //Push the name of the material to an array
  100210. //This is indispensable for the importMesh function
  100211. materialToUse.push(meshesFromObj[j].materialName);
  100212. var vertexData = new BABYLON.VertexData(); //The container for the values
  100213. //Set the data for the babylonMesh
  100214. vertexData.positions = handledMesh.positions;
  100215. vertexData.normals = handledMesh.normals;
  100216. vertexData.uvs = handledMesh.uvs;
  100217. vertexData.indices = handledMesh.indices;
  100218. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  100219. vertexData.applyToMesh(babylonMesh);
  100220. //Push the mesh into an array
  100221. babylonMeshesArray.push(babylonMesh);
  100222. }
  100223. //load the materials
  100224. //Check if we have a file to load
  100225. if (fileToLoad !== "") {
  100226. //Load the file synchronously
  100227. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  100228. //Create materials thanks MTLLoader function
  100229. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  100230. //Look at each material loaded in the mtl file
  100231. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  100232. //Three variables to get all meshes with the same material
  100233. var startIndex = 0;
  100234. var _indices = [];
  100235. var _index;
  100236. //The material from MTL file is used in the meshes loaded
  100237. //Push the indice in an array
  100238. //Check if the material is not used for another mesh
  100239. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  100240. _indices.push(_index);
  100241. startIndex = _index + 1;
  100242. }
  100243. //If the material is not used dispose it
  100244. if (_index == -1 && _indices.length == 0) {
  100245. //If the material is not needed, remove it
  100246. materialsFromMTLFile.materials[n].dispose();
  100247. }
  100248. else {
  100249. for (var o = 0; o < _indices.length; o++) {
  100250. //Apply the material to the BABYLON.Mesh for each mesh with the material
  100251. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  100252. }
  100253. }
  100254. }
  100255. });
  100256. }
  100257. //Return an array with all BABYLON.Mesh
  100258. return babylonMeshesArray;
  100259. };
  100260. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  100261. return OBJFileLoader;
  100262. }());
  100263. BABYLON.OBJFileLoader = OBJFileLoader;
  100264. if (BABYLON.SceneLoader) {
  100265. //Add this loader into the register plugin
  100266. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  100267. }
  100268. })(BABYLON || (BABYLON = {}));
  100269. //# sourceMappingURL=babylon.objFileLoader.js.map
  100270. var BABYLON;
  100271. (function (BABYLON) {
  100272. var GLTFLoaderCoordinateSystemMode;
  100273. (function (GLTFLoaderCoordinateSystemMode) {
  100274. /**
  100275. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  100276. */
  100277. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  100278. /**
  100279. * Sets the useRightHandedSystem flag on the scene.
  100280. */
  100281. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  100282. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  100283. var GLTFLoaderAnimationStartMode;
  100284. (function (GLTFLoaderAnimationStartMode) {
  100285. /**
  100286. * No animation will start.
  100287. */
  100288. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  100289. /**
  100290. * The first animation will start.
  100291. */
  100292. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  100293. /**
  100294. * All animations will start.
  100295. */
  100296. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  100297. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  100298. var GLTFLoaderState;
  100299. (function (GLTFLoaderState) {
  100300. /**
  100301. * The asset is loading.
  100302. */
  100303. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  100304. /**
  100305. * The asset is ready for rendering.
  100306. */
  100307. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  100308. /**
  100309. * The asset is completely loaded.
  100310. */
  100311. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  100312. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  100313. var GLTFFileLoader = /** @class */ (function () {
  100314. function GLTFFileLoader() {
  100315. // #region Common options
  100316. /**
  100317. * Raised when the asset has been parsed.
  100318. * The data.json property stores the glTF JSON.
  100319. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  100320. */
  100321. this.onParsedObservable = new BABYLON.Observable();
  100322. // #endregion
  100323. // #region V2 options
  100324. /**
  100325. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  100326. */
  100327. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  100328. /**
  100329. * The animation start mode (NONE, FIRST, ALL).
  100330. */
  100331. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  100332. /**
  100333. * Set to true to compile materials before raising the success callback.
  100334. */
  100335. this.compileMaterials = false;
  100336. /**
  100337. * Set to true to also compile materials with clip planes.
  100338. */
  100339. this.useClipPlane = false;
  100340. /**
  100341. * Set to true to compile shadow generators before raising the success callback.
  100342. */
  100343. this.compileShadowGenerators = false;
  100344. /**
  100345. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100346. */
  100347. this.onMeshLoadedObservable = new BABYLON.Observable();
  100348. /**
  100349. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  100350. */
  100351. this.onTextureLoadedObservable = new BABYLON.Observable();
  100352. /**
  100353. * Raised when the loader creates a material after parsing the glTF properties of the material.
  100354. */
  100355. this.onMaterialLoadedObservable = new BABYLON.Observable();
  100356. /**
  100357. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  100358. * For assets with LODs, raised when all of the LODs are complete.
  100359. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  100360. */
  100361. this.onCompleteObservable = new BABYLON.Observable();
  100362. /**
  100363. * Raised after the loader is disposed.
  100364. */
  100365. this.onDisposeObservable = new BABYLON.Observable();
  100366. /**
  100367. * Raised after a loader extension is created.
  100368. * Set additional options for a loader extension in this event.
  100369. */
  100370. this.onExtensionLoadedObservable = new BABYLON.Observable();
  100371. // #endregion
  100372. this._loader = null;
  100373. this.name = "gltf";
  100374. this.extensions = {
  100375. ".gltf": { isBinary: false },
  100376. ".glb": { isBinary: true }
  100377. };
  100378. }
  100379. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  100380. set: function (callback) {
  100381. if (this._onParsedObserver) {
  100382. this.onParsedObservable.remove(this._onParsedObserver);
  100383. }
  100384. this._onParsedObserver = this.onParsedObservable.add(callback);
  100385. },
  100386. enumerable: true,
  100387. configurable: true
  100388. });
  100389. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  100390. set: function (callback) {
  100391. if (this._onMeshLoadedObserver) {
  100392. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  100393. }
  100394. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  100395. },
  100396. enumerable: true,
  100397. configurable: true
  100398. });
  100399. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  100400. set: function (callback) {
  100401. if (this._onTextureLoadedObserver) {
  100402. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  100403. }
  100404. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  100405. },
  100406. enumerable: true,
  100407. configurable: true
  100408. });
  100409. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  100410. set: function (callback) {
  100411. if (this._onMaterialLoadedObserver) {
  100412. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  100413. }
  100414. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  100415. },
  100416. enumerable: true,
  100417. configurable: true
  100418. });
  100419. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  100420. set: function (callback) {
  100421. if (this._onCompleteObserver) {
  100422. this.onCompleteObservable.remove(this._onCompleteObserver);
  100423. }
  100424. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  100425. },
  100426. enumerable: true,
  100427. configurable: true
  100428. });
  100429. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  100430. set: function (callback) {
  100431. if (this._onDisposeObserver) {
  100432. this.onDisposeObservable.remove(this._onDisposeObserver);
  100433. }
  100434. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100435. },
  100436. enumerable: true,
  100437. configurable: true
  100438. });
  100439. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  100440. set: function (callback) {
  100441. if (this._onExtensionLoadedObserver) {
  100442. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  100443. }
  100444. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  100445. },
  100446. enumerable: true,
  100447. configurable: true
  100448. });
  100449. /**
  100450. * Returns a promise that resolves when the asset is completely loaded.
  100451. * @returns A promise that resolves when the asset is completely loaded.
  100452. */
  100453. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  100454. var _this = this;
  100455. return new Promise(function (resolve) {
  100456. _this.onCompleteObservable.add(function () {
  100457. resolve();
  100458. }, undefined, undefined, undefined, true);
  100459. });
  100460. };
  100461. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  100462. /**
  100463. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  100464. */
  100465. get: function () {
  100466. return this._loader ? this._loader.state : null;
  100467. },
  100468. enumerable: true,
  100469. configurable: true
  100470. });
  100471. /**
  100472. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  100473. */
  100474. GLTFFileLoader.prototype.dispose = function () {
  100475. if (this._loader) {
  100476. this._loader.dispose();
  100477. this._loader = null;
  100478. }
  100479. this.onMeshLoadedObservable.clear();
  100480. this.onTextureLoadedObservable.clear();
  100481. this.onMaterialLoadedObservable.clear();
  100482. this.onDisposeObservable.notifyObservers(this);
  100483. this.onDisposeObservable.clear();
  100484. };
  100485. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  100486. var _this = this;
  100487. return Promise.resolve().then(function () {
  100488. var loaderData = _this._parse(data);
  100489. _this._loader = _this._getLoader(loaderData);
  100490. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  100491. });
  100492. };
  100493. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  100494. var _this = this;
  100495. return Promise.resolve().then(function () {
  100496. var loaderData = _this._parse(data);
  100497. _this._loader = _this._getLoader(loaderData);
  100498. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  100499. });
  100500. };
  100501. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  100502. var _this = this;
  100503. return Promise.resolve().then(function () {
  100504. var loaderData = _this._parse(data);
  100505. _this._loader = _this._getLoader(loaderData);
  100506. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  100507. var container = new BABYLON.AssetContainer(scene);
  100508. Array.prototype.push.apply(container.meshes, result.meshes);
  100509. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  100510. Array.prototype.push.apply(container.skeletons, result.skeletons);
  100511. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  100512. container.removeAllFromScene();
  100513. return container;
  100514. });
  100515. });
  100516. };
  100517. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  100518. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  100519. };
  100520. GLTFFileLoader.prototype.createPlugin = function () {
  100521. return new GLTFFileLoader();
  100522. };
  100523. GLTFFileLoader.prototype._parse = function (data) {
  100524. var parsedData;
  100525. if (data instanceof ArrayBuffer) {
  100526. parsedData = GLTFFileLoader._parseBinary(data);
  100527. }
  100528. else {
  100529. parsedData = {
  100530. json: JSON.parse(data),
  100531. bin: null
  100532. };
  100533. }
  100534. this.onParsedObservable.notifyObservers(parsedData);
  100535. this.onParsedObservable.clear();
  100536. return parsedData;
  100537. };
  100538. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  100539. var _this = this;
  100540. var loaderVersion = { major: 2, minor: 0 };
  100541. var asset = loaderData.json.asset || {};
  100542. var version = GLTFFileLoader._parseVersion(asset.version);
  100543. if (!version) {
  100544. throw new Error("Invalid version: " + asset.version);
  100545. }
  100546. if (asset.minVersion !== undefined) {
  100547. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  100548. if (!minVersion) {
  100549. throw new Error("Invalid minimum version: " + asset.minVersion);
  100550. }
  100551. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  100552. throw new Error("Incompatible minimum version: " + asset.minVersion);
  100553. }
  100554. }
  100555. var createLoaders = {
  100556. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  100557. 2: GLTFFileLoader.CreateGLTFLoaderV2
  100558. };
  100559. var createLoader = createLoaders[version.major];
  100560. if (!createLoader) {
  100561. throw new Error("Unsupported version: " + asset.version);
  100562. }
  100563. var loader = createLoader();
  100564. loader.coordinateSystemMode = this.coordinateSystemMode;
  100565. loader.animationStartMode = this.animationStartMode;
  100566. loader.compileMaterials = this.compileMaterials;
  100567. loader.useClipPlane = this.useClipPlane;
  100568. loader.compileShadowGenerators = this.compileShadowGenerators;
  100569. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  100570. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  100571. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  100572. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  100573. loader.onCompleteObservable.add(function () {
  100574. _this.onMeshLoadedObservable.clear();
  100575. _this.onTextureLoadedObservable.clear();
  100576. _this.onMaterialLoadedObservable.clear();
  100577. _this.onCompleteObservable.notifyObservers(_this);
  100578. _this.onCompleteObservable.clear();
  100579. });
  100580. return loader;
  100581. };
  100582. GLTFFileLoader._parseBinary = function (data) {
  100583. var Binary = {
  100584. Magic: 0x46546C67
  100585. };
  100586. var binaryReader = new BinaryReader(data);
  100587. var magic = binaryReader.readUint32();
  100588. if (magic !== Binary.Magic) {
  100589. throw new Error("Unexpected magic: " + magic);
  100590. }
  100591. var version = binaryReader.readUint32();
  100592. switch (version) {
  100593. case 1: return GLTFFileLoader._parseV1(binaryReader);
  100594. case 2: return GLTFFileLoader._parseV2(binaryReader);
  100595. }
  100596. throw new Error("Unsupported version: " + version);
  100597. };
  100598. GLTFFileLoader._parseV1 = function (binaryReader) {
  100599. var ContentFormat = {
  100600. JSON: 0
  100601. };
  100602. var length = binaryReader.readUint32();
  100603. if (length != binaryReader.getLength()) {
  100604. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100605. }
  100606. var contentLength = binaryReader.readUint32();
  100607. var contentFormat = binaryReader.readUint32();
  100608. var content;
  100609. switch (contentFormat) {
  100610. case ContentFormat.JSON: {
  100611. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  100612. break;
  100613. }
  100614. default: {
  100615. throw new Error("Unexpected content format: " + contentFormat);
  100616. }
  100617. }
  100618. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  100619. var body = binaryReader.readUint8Array(bytesRemaining);
  100620. return {
  100621. json: content,
  100622. bin: body
  100623. };
  100624. };
  100625. GLTFFileLoader._parseV2 = function (binaryReader) {
  100626. var ChunkFormat = {
  100627. JSON: 0x4E4F534A,
  100628. BIN: 0x004E4942
  100629. };
  100630. var length = binaryReader.readUint32();
  100631. if (length !== binaryReader.getLength()) {
  100632. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100633. }
  100634. // JSON chunk
  100635. var chunkLength = binaryReader.readUint32();
  100636. var chunkFormat = binaryReader.readUint32();
  100637. if (chunkFormat !== ChunkFormat.JSON) {
  100638. throw new Error("First chunk format is not JSON");
  100639. }
  100640. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  100641. // Look for BIN chunk
  100642. var bin = null;
  100643. while (binaryReader.getPosition() < binaryReader.getLength()) {
  100644. var chunkLength_1 = binaryReader.readUint32();
  100645. var chunkFormat_1 = binaryReader.readUint32();
  100646. switch (chunkFormat_1) {
  100647. case ChunkFormat.JSON: {
  100648. throw new Error("Unexpected JSON chunk");
  100649. }
  100650. case ChunkFormat.BIN: {
  100651. bin = binaryReader.readUint8Array(chunkLength_1);
  100652. break;
  100653. }
  100654. default: {
  100655. // ignore unrecognized chunkFormat
  100656. binaryReader.skipBytes(chunkLength_1);
  100657. break;
  100658. }
  100659. }
  100660. }
  100661. return {
  100662. json: json,
  100663. bin: bin
  100664. };
  100665. };
  100666. GLTFFileLoader._parseVersion = function (version) {
  100667. if (version === "1.0" || version === "1.0.1") {
  100668. return {
  100669. major: 1,
  100670. minor: 0
  100671. };
  100672. }
  100673. var match = (version + "").match(/^(\d+)\.(\d+)/);
  100674. if (!match) {
  100675. return null;
  100676. }
  100677. return {
  100678. major: parseInt(match[1]),
  100679. minor: parseInt(match[2])
  100680. };
  100681. };
  100682. GLTFFileLoader._compareVersion = function (a, b) {
  100683. if (a.major > b.major)
  100684. return 1;
  100685. if (a.major < b.major)
  100686. return -1;
  100687. if (a.minor > b.minor)
  100688. return 1;
  100689. if (a.minor < b.minor)
  100690. return -1;
  100691. return 0;
  100692. };
  100693. GLTFFileLoader._decodeBufferToText = function (buffer) {
  100694. var result = "";
  100695. var length = buffer.byteLength;
  100696. for (var i = 0; i < length; i++) {
  100697. result += String.fromCharCode(buffer[i]);
  100698. }
  100699. return result;
  100700. };
  100701. // #endregion
  100702. // #region V1 options
  100703. GLTFFileLoader.IncrementalLoading = true;
  100704. GLTFFileLoader.HomogeneousCoordinates = false;
  100705. return GLTFFileLoader;
  100706. }());
  100707. BABYLON.GLTFFileLoader = GLTFFileLoader;
  100708. var BinaryReader = /** @class */ (function () {
  100709. function BinaryReader(arrayBuffer) {
  100710. this._arrayBuffer = arrayBuffer;
  100711. this._dataView = new DataView(arrayBuffer);
  100712. this._byteOffset = 0;
  100713. }
  100714. BinaryReader.prototype.getPosition = function () {
  100715. return this._byteOffset;
  100716. };
  100717. BinaryReader.prototype.getLength = function () {
  100718. return this._arrayBuffer.byteLength;
  100719. };
  100720. BinaryReader.prototype.readUint32 = function () {
  100721. var value = this._dataView.getUint32(this._byteOffset, true);
  100722. this._byteOffset += 4;
  100723. return value;
  100724. };
  100725. BinaryReader.prototype.readUint8Array = function (length) {
  100726. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  100727. this._byteOffset += length;
  100728. return value;
  100729. };
  100730. BinaryReader.prototype.skipBytes = function (length) {
  100731. this._byteOffset += length;
  100732. };
  100733. return BinaryReader;
  100734. }());
  100735. if (BABYLON.SceneLoader) {
  100736. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  100737. }
  100738. })(BABYLON || (BABYLON = {}));
  100739. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  100740. var BABYLON;
  100741. (function (BABYLON) {
  100742. var GLTF1;
  100743. (function (GLTF1) {
  100744. /**
  100745. * Enums
  100746. */
  100747. var EComponentType;
  100748. (function (EComponentType) {
  100749. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  100750. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100751. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  100752. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  100753. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  100754. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  100755. var EShaderType;
  100756. (function (EShaderType) {
  100757. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  100758. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  100759. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  100760. var EParameterType;
  100761. (function (EParameterType) {
  100762. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  100763. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100764. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  100765. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  100766. EParameterType[EParameterType["INT"] = 5124] = "INT";
  100767. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  100768. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  100769. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  100770. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  100771. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  100772. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  100773. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  100774. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  100775. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  100776. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  100777. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  100778. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  100779. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  100780. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  100781. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  100782. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  100783. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  100784. var ETextureWrapMode;
  100785. (function (ETextureWrapMode) {
  100786. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  100787. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  100788. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  100789. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  100790. var ETextureFilterType;
  100791. (function (ETextureFilterType) {
  100792. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  100793. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  100794. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  100795. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  100796. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  100797. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  100798. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  100799. var ETextureFormat;
  100800. (function (ETextureFormat) {
  100801. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  100802. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  100803. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  100804. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  100805. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  100806. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  100807. var ECullingType;
  100808. (function (ECullingType) {
  100809. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  100810. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  100811. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  100812. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  100813. var EBlendingFunction;
  100814. (function (EBlendingFunction) {
  100815. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  100816. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  100817. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  100818. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  100819. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  100820. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  100821. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  100822. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  100823. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  100824. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  100825. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  100826. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  100827. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  100828. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  100829. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  100830. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  100831. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100832. })(BABYLON || (BABYLON = {}));
  100833. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  100834. var BABYLON;
  100835. (function (BABYLON) {
  100836. var GLTF1;
  100837. (function (GLTF1) {
  100838. /**
  100839. * Tokenizer. Used for shaders compatibility
  100840. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  100841. */
  100842. var ETokenType;
  100843. (function (ETokenType) {
  100844. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  100845. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  100846. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  100847. })(ETokenType || (ETokenType = {}));
  100848. var Tokenizer = /** @class */ (function () {
  100849. function Tokenizer(toParse) {
  100850. this._pos = 0;
  100851. this.currentToken = ETokenType.UNKNOWN;
  100852. this.currentIdentifier = "";
  100853. this.currentString = "";
  100854. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  100855. this._toParse = toParse;
  100856. this._maxPos = toParse.length;
  100857. }
  100858. Tokenizer.prototype.getNextToken = function () {
  100859. if (this.isEnd())
  100860. return ETokenType.END_OF_INPUT;
  100861. this.currentString = this.read();
  100862. this.currentToken = ETokenType.UNKNOWN;
  100863. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  100864. this.currentToken = ETokenType.IDENTIFIER;
  100865. this.currentIdentifier = this.currentString;
  100866. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  100867. this.currentIdentifier += this.currentString;
  100868. this.forward();
  100869. }
  100870. }
  100871. return this.currentToken;
  100872. };
  100873. Tokenizer.prototype.peek = function () {
  100874. return this._toParse[this._pos];
  100875. };
  100876. Tokenizer.prototype.read = function () {
  100877. return this._toParse[this._pos++];
  100878. };
  100879. Tokenizer.prototype.forward = function () {
  100880. this._pos++;
  100881. };
  100882. Tokenizer.prototype.isEnd = function () {
  100883. return this._pos >= this._maxPos;
  100884. };
  100885. return Tokenizer;
  100886. }());
  100887. /**
  100888. * Values
  100889. */
  100890. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  100891. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  100892. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  100893. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  100894. /**
  100895. * Parse
  100896. */
  100897. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  100898. for (var buf in parsedBuffers) {
  100899. var parsedBuffer = parsedBuffers[buf];
  100900. gltfRuntime.buffers[buf] = parsedBuffer;
  100901. gltfRuntime.buffersCount++;
  100902. }
  100903. };
  100904. var parseShaders = function (parsedShaders, gltfRuntime) {
  100905. for (var sha in parsedShaders) {
  100906. var parsedShader = parsedShaders[sha];
  100907. gltfRuntime.shaders[sha] = parsedShader;
  100908. gltfRuntime.shaderscount++;
  100909. }
  100910. };
  100911. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  100912. for (var object in parsedObjects) {
  100913. var parsedObject = parsedObjects[object];
  100914. gltfRuntime[runtimeProperty][object] = parsedObject;
  100915. }
  100916. };
  100917. /**
  100918. * Utils
  100919. */
  100920. var normalizeUVs = function (buffer) {
  100921. if (!buffer) {
  100922. return;
  100923. }
  100924. for (var i = 0; i < buffer.length / 2; i++) {
  100925. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  100926. }
  100927. };
  100928. var getAttribute = function (attributeParameter) {
  100929. if (attributeParameter.semantic === "NORMAL") {
  100930. return "normal";
  100931. }
  100932. else if (attributeParameter.semantic === "POSITION") {
  100933. return "position";
  100934. }
  100935. else if (attributeParameter.semantic === "JOINT") {
  100936. return "matricesIndices";
  100937. }
  100938. else if (attributeParameter.semantic === "WEIGHT") {
  100939. return "matricesWeights";
  100940. }
  100941. else if (attributeParameter.semantic === "COLOR") {
  100942. return "color";
  100943. }
  100944. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  100945. var channel = Number(attributeParameter.semantic.split("_")[1]);
  100946. return "uv" + (channel === 0 ? "" : channel + 1);
  100947. }
  100948. return null;
  100949. };
  100950. /**
  100951. * Loads and creates animations
  100952. */
  100953. var loadAnimations = function (gltfRuntime) {
  100954. for (var anim in gltfRuntime.animations) {
  100955. var animation = gltfRuntime.animations[anim];
  100956. if (!animation.channels || !animation.samplers) {
  100957. continue;
  100958. }
  100959. var lastAnimation = null;
  100960. for (var i = 0; i < animation.channels.length; i++) {
  100961. // Get parameters and load buffers
  100962. var channel = animation.channels[i];
  100963. var sampler = animation.samplers[channel.sampler];
  100964. if (!sampler) {
  100965. continue;
  100966. }
  100967. var inputData = null;
  100968. var outputData = null;
  100969. if (animation.parameters) {
  100970. inputData = animation.parameters[sampler.input];
  100971. outputData = animation.parameters[sampler.output];
  100972. }
  100973. else {
  100974. inputData = sampler.input;
  100975. outputData = sampler.output;
  100976. }
  100977. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  100978. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  100979. var targetID = channel.target.id;
  100980. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  100981. if (targetNode === null) {
  100982. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  100983. }
  100984. if (targetNode === null) {
  100985. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  100986. continue;
  100987. }
  100988. var isBone = targetNode instanceof BABYLON.Bone;
  100989. // Get target path (position, rotation or scaling)
  100990. var targetPath = channel.target.path;
  100991. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  100992. if (targetPathIndex !== -1) {
  100993. targetPath = babylonAnimationPaths[targetPathIndex];
  100994. }
  100995. // Determine animation type
  100996. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  100997. if (!isBone) {
  100998. if (targetPath === "rotationQuaternion") {
  100999. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101000. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  101001. }
  101002. else {
  101003. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101004. }
  101005. }
  101006. // Create animation and key frames
  101007. var babylonAnimation = null;
  101008. var keys = [];
  101009. var arrayOffset = 0;
  101010. var modifyKey = false;
  101011. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  101012. babylonAnimation = lastAnimation;
  101013. modifyKey = true;
  101014. }
  101015. if (!modifyKey) {
  101016. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101017. }
  101018. // For each frame
  101019. for (var j = 0; j < bufferInput.length; j++) {
  101020. var value = null;
  101021. if (targetPath === "rotationQuaternion") { // VEC4
  101022. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101023. arrayOffset += 4;
  101024. }
  101025. else { // Position and scaling are VEC3
  101026. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  101027. arrayOffset += 3;
  101028. }
  101029. if (isBone) {
  101030. var bone = targetNode;
  101031. var translation = BABYLON.Vector3.Zero();
  101032. var rotationQuaternion = new BABYLON.Quaternion();
  101033. var scaling = BABYLON.Vector3.Zero();
  101034. // Warning on decompose
  101035. var mat = bone.getBaseMatrix();
  101036. if (modifyKey && lastAnimation) {
  101037. mat = lastAnimation.getKeys()[j].value;
  101038. }
  101039. mat.decompose(scaling, rotationQuaternion, translation);
  101040. if (targetPath === "position") {
  101041. translation = value;
  101042. }
  101043. else if (targetPath === "rotationQuaternion") {
  101044. rotationQuaternion = value;
  101045. }
  101046. else {
  101047. scaling = value;
  101048. }
  101049. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  101050. }
  101051. if (!modifyKey) {
  101052. keys.push({
  101053. frame: bufferInput[j],
  101054. value: value
  101055. });
  101056. }
  101057. else if (lastAnimation) {
  101058. lastAnimation.getKeys()[j].value = value;
  101059. }
  101060. }
  101061. // Finish
  101062. if (!modifyKey && babylonAnimation) {
  101063. babylonAnimation.setKeys(keys);
  101064. targetNode.animations.push(babylonAnimation);
  101065. }
  101066. lastAnimation = babylonAnimation;
  101067. gltfRuntime.scene.stopAnimation(targetNode);
  101068. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  101069. }
  101070. }
  101071. };
  101072. /**
  101073. * Returns the bones transformation matrix
  101074. */
  101075. var configureBoneTransformation = function (node) {
  101076. var mat = null;
  101077. if (node.translation || node.rotation || node.scale) {
  101078. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  101079. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  101080. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  101081. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  101082. }
  101083. else {
  101084. mat = BABYLON.Matrix.FromArray(node.matrix);
  101085. }
  101086. return mat;
  101087. };
  101088. /**
  101089. * Returns the parent bone
  101090. */
  101091. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  101092. // Try to find
  101093. for (var i = 0; i < newSkeleton.bones.length; i++) {
  101094. if (newSkeleton.bones[i].name === jointName) {
  101095. return newSkeleton.bones[i];
  101096. }
  101097. }
  101098. // Not found, search in gltf nodes
  101099. var nodes = gltfRuntime.nodes;
  101100. for (var nde in nodes) {
  101101. var node = nodes[nde];
  101102. if (!node.jointName) {
  101103. continue;
  101104. }
  101105. var children = node.children;
  101106. for (var i = 0; i < children.length; i++) {
  101107. var child = gltfRuntime.nodes[children[i]];
  101108. if (!child.jointName) {
  101109. continue;
  101110. }
  101111. if (child.jointName === jointName) {
  101112. var mat = configureBoneTransformation(node);
  101113. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  101114. bone.id = nde;
  101115. return bone;
  101116. }
  101117. }
  101118. }
  101119. return null;
  101120. };
  101121. /**
  101122. * Returns the appropriate root node
  101123. */
  101124. var getNodeToRoot = function (nodesToRoot, id) {
  101125. for (var i = 0; i < nodesToRoot.length; i++) {
  101126. var nodeToRoot = nodesToRoot[i];
  101127. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  101128. var child = nodeToRoot.node.children[j];
  101129. if (child === id) {
  101130. return nodeToRoot.bone;
  101131. }
  101132. }
  101133. }
  101134. return null;
  101135. };
  101136. /**
  101137. * Returns the node with the joint name
  101138. */
  101139. var getJointNode = function (gltfRuntime, jointName) {
  101140. var nodes = gltfRuntime.nodes;
  101141. var node = nodes[jointName];
  101142. if (node) {
  101143. return {
  101144. node: node,
  101145. id: jointName
  101146. };
  101147. }
  101148. for (var nde in nodes) {
  101149. node = nodes[nde];
  101150. if (node.jointName === jointName) {
  101151. return {
  101152. node: node,
  101153. id: nde
  101154. };
  101155. }
  101156. }
  101157. return null;
  101158. };
  101159. /**
  101160. * Checks if a nodes is in joints
  101161. */
  101162. var nodeIsInJoints = function (skins, id) {
  101163. for (var i = 0; i < skins.jointNames.length; i++) {
  101164. if (skins.jointNames[i] === id) {
  101165. return true;
  101166. }
  101167. }
  101168. return false;
  101169. };
  101170. /**
  101171. * Fills the nodes to root for bones and builds hierarchy
  101172. */
  101173. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  101174. // Creates nodes for root
  101175. for (var nde in gltfRuntime.nodes) {
  101176. var node = gltfRuntime.nodes[nde];
  101177. var id = nde;
  101178. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  101179. continue;
  101180. }
  101181. // Create node to root bone
  101182. var mat = configureBoneTransformation(node);
  101183. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  101184. bone.id = id;
  101185. nodesToRoot.push({ bone: bone, node: node, id: id });
  101186. }
  101187. // Parenting
  101188. for (var i = 0; i < nodesToRoot.length; i++) {
  101189. var nodeToRoot = nodesToRoot[i];
  101190. var children = nodeToRoot.node.children;
  101191. for (var j = 0; j < children.length; j++) {
  101192. var child = null;
  101193. for (var k = 0; k < nodesToRoot.length; k++) {
  101194. if (nodesToRoot[k].id === children[j]) {
  101195. child = nodesToRoot[k];
  101196. break;
  101197. }
  101198. }
  101199. if (child) {
  101200. child.bone._parent = nodeToRoot.bone;
  101201. nodeToRoot.bone.children.push(child.bone);
  101202. }
  101203. }
  101204. }
  101205. };
  101206. /**
  101207. * Imports a skeleton
  101208. */
  101209. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  101210. if (!newSkeleton) {
  101211. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  101212. }
  101213. if (!skins.babylonSkeleton) {
  101214. return newSkeleton;
  101215. }
  101216. // Find the root bones
  101217. var nodesToRoot = [];
  101218. var nodesToRootToAdd = [];
  101219. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  101220. newSkeleton.bones = [];
  101221. // Joints
  101222. for (var i = 0; i < skins.jointNames.length; i++) {
  101223. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101224. if (!jointNode) {
  101225. continue;
  101226. }
  101227. var node = jointNode.node;
  101228. if (!node) {
  101229. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  101230. continue;
  101231. }
  101232. var id = jointNode.id;
  101233. // Optimize, if the bone already exists...
  101234. var existingBone = gltfRuntime.scene.getBoneByID(id);
  101235. if (existingBone) {
  101236. newSkeleton.bones.push(existingBone);
  101237. continue;
  101238. }
  101239. // Search for parent bone
  101240. var foundBone = false;
  101241. var parentBone = null;
  101242. for (var j = 0; j < i; j++) {
  101243. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  101244. if (!jointNode_1) {
  101245. continue;
  101246. }
  101247. var joint = jointNode_1.node;
  101248. if (!joint) {
  101249. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  101250. continue;
  101251. }
  101252. var children = joint.children;
  101253. if (!children) {
  101254. continue;
  101255. }
  101256. foundBone = false;
  101257. for (var k = 0; k < children.length; k++) {
  101258. if (children[k] === id) {
  101259. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  101260. foundBone = true;
  101261. break;
  101262. }
  101263. }
  101264. if (foundBone) {
  101265. break;
  101266. }
  101267. }
  101268. // Create bone
  101269. var mat = configureBoneTransformation(node);
  101270. if (!parentBone && nodesToRoot.length > 0) {
  101271. parentBone = getNodeToRoot(nodesToRoot, id);
  101272. if (parentBone) {
  101273. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  101274. nodesToRootToAdd.push(parentBone);
  101275. }
  101276. }
  101277. }
  101278. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  101279. bone.id = id;
  101280. }
  101281. // Polish
  101282. var bones = newSkeleton.bones;
  101283. newSkeleton.bones = [];
  101284. for (var i = 0; i < skins.jointNames.length; i++) {
  101285. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101286. if (!jointNode) {
  101287. continue;
  101288. }
  101289. for (var j = 0; j < bones.length; j++) {
  101290. if (bones[j].id === jointNode.id) {
  101291. newSkeleton.bones.push(bones[j]);
  101292. break;
  101293. }
  101294. }
  101295. }
  101296. newSkeleton.prepare();
  101297. // Finish
  101298. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  101299. newSkeleton.bones.push(nodesToRootToAdd[i]);
  101300. }
  101301. return newSkeleton;
  101302. };
  101303. /**
  101304. * Imports a mesh and its geometries
  101305. */
  101306. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  101307. if (!newMesh) {
  101308. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101309. newMesh.id = id;
  101310. }
  101311. if (!node.babylonNode) {
  101312. return newMesh;
  101313. }
  101314. var subMaterials = [];
  101315. var vertexData = null;
  101316. var verticesStarts = new Array();
  101317. var verticesCounts = new Array();
  101318. var indexStarts = new Array();
  101319. var indexCounts = new Array();
  101320. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101321. var meshID = meshes[meshIndex];
  101322. var mesh = gltfRuntime.meshes[meshID];
  101323. if (!mesh) {
  101324. continue;
  101325. }
  101326. // Positions, normals and UVs
  101327. for (var i = 0; i < mesh.primitives.length; i++) {
  101328. // Temporary vertex data
  101329. var tempVertexData = new BABYLON.VertexData();
  101330. var primitive = mesh.primitives[i];
  101331. if (primitive.mode !== 4) {
  101332. // continue;
  101333. }
  101334. var attributes = primitive.attributes;
  101335. var accessor = null;
  101336. var buffer = null;
  101337. // Set positions, normal and uvs
  101338. for (var semantic in attributes) {
  101339. // Link accessor and buffer view
  101340. accessor = gltfRuntime.accessors[attributes[semantic]];
  101341. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101342. if (semantic === "NORMAL") {
  101343. tempVertexData.normals = new Float32Array(buffer.length);
  101344. tempVertexData.normals.set(buffer);
  101345. }
  101346. else if (semantic === "POSITION") {
  101347. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  101348. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  101349. for (var j = 0; j < buffer.length; j += 4) {
  101350. tempVertexData.positions[j] = buffer[j];
  101351. tempVertexData.positions[j + 1] = buffer[j + 1];
  101352. tempVertexData.positions[j + 2] = buffer[j + 2];
  101353. }
  101354. }
  101355. else {
  101356. tempVertexData.positions = new Float32Array(buffer.length);
  101357. tempVertexData.positions.set(buffer);
  101358. }
  101359. verticesCounts.push(tempVertexData.positions.length);
  101360. }
  101361. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  101362. var channel = Number(semantic.split("_")[1]);
  101363. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  101364. var uvs = new Float32Array(buffer.length);
  101365. uvs.set(buffer);
  101366. normalizeUVs(uvs);
  101367. tempVertexData.set(uvs, uvKind);
  101368. }
  101369. else if (semantic === "JOINT") {
  101370. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  101371. tempVertexData.matricesIndices.set(buffer);
  101372. }
  101373. else if (semantic === "WEIGHT") {
  101374. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  101375. tempVertexData.matricesWeights.set(buffer);
  101376. }
  101377. else if (semantic === "COLOR") {
  101378. tempVertexData.colors = new Float32Array(buffer.length);
  101379. tempVertexData.colors.set(buffer);
  101380. }
  101381. }
  101382. // Indices
  101383. accessor = gltfRuntime.accessors[primitive.indices];
  101384. if (accessor) {
  101385. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101386. tempVertexData.indices = new Int32Array(buffer.length);
  101387. tempVertexData.indices.set(buffer);
  101388. indexCounts.push(tempVertexData.indices.length);
  101389. }
  101390. else {
  101391. // Set indices on the fly
  101392. var indices = [];
  101393. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  101394. indices.push(j);
  101395. }
  101396. tempVertexData.indices = new Int32Array(indices);
  101397. indexCounts.push(tempVertexData.indices.length);
  101398. }
  101399. if (!vertexData) {
  101400. vertexData = tempVertexData;
  101401. }
  101402. else {
  101403. vertexData.merge(tempVertexData);
  101404. }
  101405. // Sub material
  101406. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  101407. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  101408. // Update vertices start and index start
  101409. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  101410. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  101411. }
  101412. }
  101413. var material;
  101414. if (subMaterials.length > 1) {
  101415. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  101416. material.subMaterials = subMaterials;
  101417. }
  101418. else {
  101419. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  101420. }
  101421. if (subMaterials.length === 1) {
  101422. material = subMaterials[0];
  101423. }
  101424. if (!newMesh.material) {
  101425. newMesh.material = material;
  101426. }
  101427. // Apply geometry
  101428. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  101429. newMesh.computeWorldMatrix(true);
  101430. // Apply submeshes
  101431. newMesh.subMeshes = [];
  101432. var index = 0;
  101433. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101434. var meshID = meshes[meshIndex];
  101435. var mesh = gltfRuntime.meshes[meshID];
  101436. if (!mesh) {
  101437. continue;
  101438. }
  101439. for (var i = 0; i < mesh.primitives.length; i++) {
  101440. if (mesh.primitives[i].mode !== 4) {
  101441. //continue;
  101442. }
  101443. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  101444. index++;
  101445. }
  101446. }
  101447. // Finish
  101448. return newMesh;
  101449. };
  101450. /**
  101451. * Configure node transformation from position, rotation and scaling
  101452. */
  101453. var configureNode = function (newNode, position, rotation, scaling) {
  101454. if (newNode.position) {
  101455. newNode.position = position;
  101456. }
  101457. if (newNode.rotationQuaternion || newNode.rotation) {
  101458. newNode.rotationQuaternion = rotation;
  101459. }
  101460. if (newNode.scaling) {
  101461. newNode.scaling = scaling;
  101462. }
  101463. };
  101464. /**
  101465. * Configures node from transformation matrix
  101466. */
  101467. var configureNodeFromMatrix = function (newNode, node, parent) {
  101468. if (node.matrix) {
  101469. var position = new BABYLON.Vector3(0, 0, 0);
  101470. var rotation = new BABYLON.Quaternion();
  101471. var scaling = new BABYLON.Vector3(0, 0, 0);
  101472. var mat = BABYLON.Matrix.FromArray(node.matrix);
  101473. mat.decompose(scaling, rotation, position);
  101474. configureNode(newNode, position, rotation, scaling);
  101475. }
  101476. else if (node.translation && node.rotation && node.scale) {
  101477. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  101478. }
  101479. newNode.computeWorldMatrix(true);
  101480. };
  101481. /**
  101482. * Imports a node
  101483. */
  101484. var importNode = function (gltfRuntime, node, id, parent) {
  101485. var lastNode = null;
  101486. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  101487. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  101488. return null;
  101489. }
  101490. }
  101491. // Meshes
  101492. if (node.skin) {
  101493. if (node.meshes) {
  101494. var skin = gltfRuntime.skins[node.skin];
  101495. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  101496. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  101497. if (newMesh.skeleton === null) {
  101498. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  101499. if (!skin.babylonSkeleton) {
  101500. skin.babylonSkeleton = newMesh.skeleton;
  101501. }
  101502. }
  101503. lastNode = newMesh;
  101504. }
  101505. }
  101506. else if (node.meshes) {
  101507. /**
  101508. * Improve meshes property
  101509. */
  101510. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  101511. lastNode = newMesh;
  101512. }
  101513. // Lights
  101514. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101515. var light = gltfRuntime.lights[node.light];
  101516. if (light) {
  101517. if (light.type === "ambient") {
  101518. var ambienLight = light[light.type];
  101519. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101520. hemiLight.name = node.name || "";
  101521. if (ambienLight.color) {
  101522. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  101523. }
  101524. lastNode = hemiLight;
  101525. }
  101526. else if (light.type === "directional") {
  101527. var directionalLight = light[light.type];
  101528. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101529. dirLight.name = node.name || "";
  101530. if (directionalLight.color) {
  101531. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  101532. }
  101533. lastNode = dirLight;
  101534. }
  101535. else if (light.type === "point") {
  101536. var pointLight = light[light.type];
  101537. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101538. ptLight.name = node.name || "";
  101539. if (pointLight.color) {
  101540. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  101541. }
  101542. lastNode = ptLight;
  101543. }
  101544. else if (light.type === "spot") {
  101545. var spotLight = light[light.type];
  101546. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  101547. spLight.name = node.name || "";
  101548. if (spotLight.color) {
  101549. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  101550. }
  101551. if (spotLight.fallOfAngle) {
  101552. spLight.angle = spotLight.fallOfAngle;
  101553. }
  101554. if (spotLight.fallOffExponent) {
  101555. spLight.exponent = spotLight.fallOffExponent;
  101556. }
  101557. lastNode = spLight;
  101558. }
  101559. }
  101560. }
  101561. // Cameras
  101562. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101563. var camera = gltfRuntime.cameras[node.camera];
  101564. if (camera) {
  101565. if (camera.type === "orthographic") {
  101566. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101567. orthoCamera.name = node.name || "";
  101568. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  101569. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101570. lastNode = orthoCamera;
  101571. }
  101572. else if (camera.type === "perspective") {
  101573. var perspectiveCamera = camera[camera.type];
  101574. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101575. persCamera.name = node.name || "";
  101576. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101577. if (!perspectiveCamera.aspectRatio) {
  101578. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  101579. }
  101580. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  101581. persCamera.maxZ = perspectiveCamera.zfar;
  101582. persCamera.minZ = perspectiveCamera.znear;
  101583. }
  101584. lastNode = persCamera;
  101585. }
  101586. }
  101587. }
  101588. // Empty node
  101589. if (!node.jointName) {
  101590. if (node.babylonNode) {
  101591. return node.babylonNode;
  101592. }
  101593. else if (lastNode === null) {
  101594. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101595. node.babylonNode = dummy;
  101596. lastNode = dummy;
  101597. }
  101598. }
  101599. if (lastNode !== null) {
  101600. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  101601. configureNodeFromMatrix(lastNode, node, parent);
  101602. }
  101603. else {
  101604. var translation = node.translation || [0, 0, 0];
  101605. var rotation = node.rotation || [0, 0, 0, 1];
  101606. var scale = node.scale || [1, 1, 1];
  101607. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  101608. }
  101609. lastNode.updateCache(true);
  101610. node.babylonNode = lastNode;
  101611. }
  101612. return lastNode;
  101613. };
  101614. /**
  101615. * Traverses nodes and creates them
  101616. */
  101617. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  101618. if (meshIncluded === void 0) { meshIncluded = false; }
  101619. var node = gltfRuntime.nodes[id];
  101620. var newNode = null;
  101621. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  101622. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  101623. meshIncluded = true;
  101624. }
  101625. else {
  101626. meshIncluded = false;
  101627. }
  101628. }
  101629. else {
  101630. meshIncluded = true;
  101631. }
  101632. if (!node.jointName && meshIncluded) {
  101633. newNode = importNode(gltfRuntime, node, id, parent);
  101634. if (newNode !== null) {
  101635. newNode.id = id;
  101636. newNode.parent = parent;
  101637. }
  101638. }
  101639. if (node.children) {
  101640. for (var i = 0; i < node.children.length; i++) {
  101641. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  101642. }
  101643. }
  101644. };
  101645. /**
  101646. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  101647. */
  101648. var postLoad = function (gltfRuntime) {
  101649. // Nodes
  101650. var currentScene = gltfRuntime.currentScene;
  101651. if (currentScene) {
  101652. for (var i = 0; i < currentScene.nodes.length; i++) {
  101653. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  101654. }
  101655. }
  101656. else {
  101657. for (var thing in gltfRuntime.scenes) {
  101658. currentScene = gltfRuntime.scenes[thing];
  101659. for (var i = 0; i < currentScene.nodes.length; i++) {
  101660. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  101661. }
  101662. }
  101663. }
  101664. // Set animations
  101665. loadAnimations(gltfRuntime);
  101666. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  101667. var skeleton = gltfRuntime.scene.skeletons[i];
  101668. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  101669. }
  101670. };
  101671. /**
  101672. * onBind shaderrs callback to set uniforms and matrices
  101673. */
  101674. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  101675. var materialValues = material.values || technique.parameters;
  101676. for (var unif in unTreatedUniforms) {
  101677. var uniform = unTreatedUniforms[unif];
  101678. var type = uniform.type;
  101679. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  101680. if (uniform.semantic && !uniform.source && !uniform.node) {
  101681. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  101682. }
  101683. else if (uniform.semantic && (uniform.source || uniform.node)) {
  101684. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  101685. if (source === null) {
  101686. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  101687. }
  101688. if (source === null) {
  101689. continue;
  101690. }
  101691. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  101692. }
  101693. }
  101694. else {
  101695. var value = materialValues[technique.uniforms[unif]];
  101696. if (!value) {
  101697. continue;
  101698. }
  101699. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  101700. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  101701. if (texture === null || texture === undefined) {
  101702. continue;
  101703. }
  101704. shaderMaterial.getEffect().setTexture(unif, texture);
  101705. }
  101706. else {
  101707. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  101708. }
  101709. }
  101710. }
  101711. onSuccess(shaderMaterial);
  101712. };
  101713. /**
  101714. * Prepare uniforms to send the only one time
  101715. * Loads the appropriate textures
  101716. */
  101717. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  101718. var materialValues = material.values || technique.parameters;
  101719. var techniqueUniforms = technique.uniforms;
  101720. /**
  101721. * Prepare values here (not matrices)
  101722. */
  101723. for (var unif in unTreatedUniforms) {
  101724. var uniform = unTreatedUniforms[unif];
  101725. var type = uniform.type;
  101726. var value = materialValues[techniqueUniforms[unif]];
  101727. if (value === undefined) {
  101728. // In case the value is the same for all materials
  101729. value = uniform.value;
  101730. }
  101731. if (!value) {
  101732. continue;
  101733. }
  101734. var onLoadTexture = function (uniformName) {
  101735. return function (texture) {
  101736. if (uniform.value && uniformName) {
  101737. // Static uniform
  101738. shaderMaterial.setTexture(uniformName, texture);
  101739. delete unTreatedUniforms[uniformName];
  101740. }
  101741. };
  101742. };
  101743. // Texture (sampler2D)
  101744. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  101745. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  101746. }
  101747. // Others
  101748. else {
  101749. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  101750. // Static uniform
  101751. delete unTreatedUniforms[unif];
  101752. }
  101753. }
  101754. }
  101755. };
  101756. /**
  101757. * Shader compilation failed
  101758. */
  101759. var onShaderCompileError = function (program, shaderMaterial, onError) {
  101760. return function (effect, error) {
  101761. shaderMaterial.dispose(true);
  101762. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  101763. };
  101764. };
  101765. /**
  101766. * Shader compilation success
  101767. */
  101768. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  101769. return function (_) {
  101770. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  101771. shaderMaterial.onBind = function (mesh) {
  101772. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  101773. };
  101774. };
  101775. };
  101776. /**
  101777. * Returns the appropriate uniform if already handled by babylon
  101778. */
  101779. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  101780. for (var unif in technique.uniforms) {
  101781. var uniform = technique.uniforms[unif];
  101782. var uniformParameter = technique.parameters[uniform];
  101783. if (tokenizer.currentIdentifier === unif) {
  101784. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  101785. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  101786. if (transformIndex !== -1) {
  101787. delete unTreatedUniforms[unif];
  101788. return babylonTransforms[transformIndex];
  101789. }
  101790. }
  101791. }
  101792. }
  101793. return tokenizer.currentIdentifier;
  101794. };
  101795. /**
  101796. * All shaders loaded. Create materials one by one
  101797. */
  101798. var importMaterials = function (gltfRuntime) {
  101799. // Create materials
  101800. for (var mat in gltfRuntime.materials) {
  101801. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  101802. }
  101803. };
  101804. /**
  101805. * Implementation of the base glTF spec
  101806. */
  101807. var GLTFLoaderBase = /** @class */ (function () {
  101808. function GLTFLoaderBase() {
  101809. }
  101810. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  101811. var gltfRuntime = {
  101812. extensions: {},
  101813. accessors: {},
  101814. buffers: {},
  101815. bufferViews: {},
  101816. meshes: {},
  101817. lights: {},
  101818. cameras: {},
  101819. nodes: {},
  101820. images: {},
  101821. textures: {},
  101822. shaders: {},
  101823. programs: {},
  101824. samplers: {},
  101825. techniques: {},
  101826. materials: {},
  101827. animations: {},
  101828. skins: {},
  101829. extensionsUsed: [],
  101830. scenes: {},
  101831. buffersCount: 0,
  101832. shaderscount: 0,
  101833. scene: scene,
  101834. rootUrl: rootUrl,
  101835. loadedBufferCount: 0,
  101836. loadedBufferViews: {},
  101837. loadedShaderCount: 0,
  101838. importOnlyMeshes: false,
  101839. dummyNodes: []
  101840. };
  101841. // Parse
  101842. if (parsedData.extensions) {
  101843. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  101844. }
  101845. if (parsedData.extensionsUsed) {
  101846. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  101847. }
  101848. if (parsedData.buffers) {
  101849. parseBuffers(parsedData.buffers, gltfRuntime);
  101850. }
  101851. if (parsedData.bufferViews) {
  101852. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  101853. }
  101854. if (parsedData.accessors) {
  101855. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  101856. }
  101857. if (parsedData.meshes) {
  101858. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  101859. }
  101860. if (parsedData.lights) {
  101861. parseObject(parsedData.lights, "lights", gltfRuntime);
  101862. }
  101863. if (parsedData.cameras) {
  101864. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  101865. }
  101866. if (parsedData.nodes) {
  101867. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  101868. }
  101869. if (parsedData.images) {
  101870. parseObject(parsedData.images, "images", gltfRuntime);
  101871. }
  101872. if (parsedData.textures) {
  101873. parseObject(parsedData.textures, "textures", gltfRuntime);
  101874. }
  101875. if (parsedData.shaders) {
  101876. parseShaders(parsedData.shaders, gltfRuntime);
  101877. }
  101878. if (parsedData.programs) {
  101879. parseObject(parsedData.programs, "programs", gltfRuntime);
  101880. }
  101881. if (parsedData.samplers) {
  101882. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  101883. }
  101884. if (parsedData.techniques) {
  101885. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  101886. }
  101887. if (parsedData.materials) {
  101888. parseObject(parsedData.materials, "materials", gltfRuntime);
  101889. }
  101890. if (parsedData.animations) {
  101891. parseObject(parsedData.animations, "animations", gltfRuntime);
  101892. }
  101893. if (parsedData.skins) {
  101894. parseObject(parsedData.skins, "skins", gltfRuntime);
  101895. }
  101896. if (parsedData.scenes) {
  101897. gltfRuntime.scenes = parsedData.scenes;
  101898. }
  101899. if (parsedData.scene && parsedData.scenes) {
  101900. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  101901. }
  101902. return gltfRuntime;
  101903. };
  101904. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  101905. var buffer = gltfRuntime.buffers[id];
  101906. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  101907. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  101908. }
  101909. else {
  101910. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  101911. if (request) {
  101912. onError(request.status + " " + request.statusText);
  101913. }
  101914. });
  101915. }
  101916. };
  101917. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  101918. var texture = gltfRuntime.textures[id];
  101919. if (!texture || !texture.source) {
  101920. onError("");
  101921. return;
  101922. }
  101923. if (texture.babylonTexture) {
  101924. onSuccess(null);
  101925. return;
  101926. }
  101927. var source = gltfRuntime.images[texture.source];
  101928. if (BABYLON.Tools.IsBase64(source.uri)) {
  101929. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  101930. }
  101931. else {
  101932. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  101933. if (request) {
  101934. onError(request.status + " " + request.statusText);
  101935. }
  101936. });
  101937. }
  101938. };
  101939. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  101940. var texture = gltfRuntime.textures[id];
  101941. if (texture.babylonTexture) {
  101942. onSuccess(texture.babylonTexture);
  101943. return;
  101944. }
  101945. var sampler = gltfRuntime.samplers[texture.sampler];
  101946. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  101947. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  101948. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  101949. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  101950. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  101951. var blob = new Blob([buffer]);
  101952. var blobURL = URL.createObjectURL(blob);
  101953. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  101954. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  101955. if (sampler.wrapS !== undefined) {
  101956. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  101957. }
  101958. if (sampler.wrapT !== undefined) {
  101959. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  101960. }
  101961. newTexture.name = id;
  101962. texture.babylonTexture = newTexture;
  101963. onSuccess(newTexture);
  101964. };
  101965. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  101966. var shader = gltfRuntime.shaders[id];
  101967. if (BABYLON.Tools.IsBase64(shader.uri)) {
  101968. var shaderString = atob(shader.uri.split(",")[1]);
  101969. if (onSuccess) {
  101970. onSuccess(shaderString);
  101971. }
  101972. }
  101973. else {
  101974. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  101975. if (request && onError) {
  101976. onError(request.status + " " + request.statusText);
  101977. }
  101978. });
  101979. }
  101980. };
  101981. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  101982. var material = gltfRuntime.materials[id];
  101983. if (!material.technique) {
  101984. if (onError) {
  101985. onError("No technique found.");
  101986. }
  101987. return;
  101988. }
  101989. var technique = gltfRuntime.techniques[material.technique];
  101990. if (!technique) {
  101991. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  101992. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  101993. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  101994. onSuccess(defaultMaterial);
  101995. return;
  101996. }
  101997. var program = gltfRuntime.programs[technique.program];
  101998. var states = technique.states;
  101999. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  102000. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  102001. var newVertexShader = "";
  102002. var newPixelShader = "";
  102003. var vertexTokenizer = new Tokenizer(vertexShader);
  102004. var pixelTokenizer = new Tokenizer(pixelShader);
  102005. var unTreatedUniforms = {};
  102006. var uniforms = [];
  102007. var attributes = [];
  102008. var samplers = [];
  102009. // Fill uniform, sampler2D and attributes
  102010. for (var unif in technique.uniforms) {
  102011. var uniform = technique.uniforms[unif];
  102012. var uniformParameter = technique.parameters[uniform];
  102013. unTreatedUniforms[unif] = uniformParameter;
  102014. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  102015. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102016. if (transformIndex !== -1) {
  102017. uniforms.push(babylonTransforms[transformIndex]);
  102018. delete unTreatedUniforms[unif];
  102019. }
  102020. else {
  102021. uniforms.push(unif);
  102022. }
  102023. }
  102024. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  102025. samplers.push(unif);
  102026. }
  102027. else {
  102028. uniforms.push(unif);
  102029. }
  102030. }
  102031. for (var attr in technique.attributes) {
  102032. var attribute = technique.attributes[attr];
  102033. var attributeParameter = technique.parameters[attribute];
  102034. if (attributeParameter.semantic) {
  102035. attributes.push(getAttribute(attributeParameter));
  102036. }
  102037. }
  102038. // Configure vertex shader
  102039. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  102040. var tokenType = vertexTokenizer.currentToken;
  102041. if (tokenType !== ETokenType.IDENTIFIER) {
  102042. newVertexShader += vertexTokenizer.currentString;
  102043. continue;
  102044. }
  102045. var foundAttribute = false;
  102046. for (var attr in technique.attributes) {
  102047. var attribute = technique.attributes[attr];
  102048. var attributeParameter = technique.parameters[attribute];
  102049. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  102050. newVertexShader += getAttribute(attributeParameter);
  102051. foundAttribute = true;
  102052. break;
  102053. }
  102054. }
  102055. if (foundAttribute) {
  102056. continue;
  102057. }
  102058. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  102059. }
  102060. // Configure pixel shader
  102061. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  102062. var tokenType = pixelTokenizer.currentToken;
  102063. if (tokenType !== ETokenType.IDENTIFIER) {
  102064. newPixelShader += pixelTokenizer.currentString;
  102065. continue;
  102066. }
  102067. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  102068. }
  102069. // Create shader material
  102070. var shaderPath = {
  102071. vertex: program.vertexShader + id,
  102072. fragment: program.fragmentShader + id
  102073. };
  102074. var options = {
  102075. attributes: attributes,
  102076. uniforms: uniforms,
  102077. samplers: samplers,
  102078. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  102079. };
  102080. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  102081. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  102082. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  102083. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  102084. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  102085. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102086. if (states && states.functions) {
  102087. var functions = states.functions;
  102088. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  102089. shaderMaterial.backFaceCulling = false;
  102090. }
  102091. var blendFunc = functions.blendFuncSeparate;
  102092. if (blendFunc) {
  102093. 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) {
  102094. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  102095. }
  102096. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102097. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  102098. }
  102099. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102100. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  102101. }
  102102. 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) {
  102103. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  102104. }
  102105. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102106. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  102107. }
  102108. 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) {
  102109. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  102110. }
  102111. }
  102112. }
  102113. };
  102114. return GLTFLoaderBase;
  102115. }());
  102116. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  102117. /**
  102118. * glTF V1 Loader
  102119. */
  102120. var GLTFLoader = /** @class */ (function () {
  102121. function GLTFLoader() {
  102122. // #region Stubs for IGLTFLoader interface
  102123. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  102124. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  102125. this.compileMaterials = false;
  102126. this.useClipPlane = false;
  102127. this.compileShadowGenerators = false;
  102128. this.onDisposeObservable = new BABYLON.Observable();
  102129. this.onMeshLoadedObservable = new BABYLON.Observable();
  102130. this.onTextureLoadedObservable = new BABYLON.Observable();
  102131. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102132. this.onCompleteObservable = new BABYLON.Observable();
  102133. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102134. this.state = null;
  102135. }
  102136. GLTFLoader.RegisterExtension = function (extension) {
  102137. if (GLTFLoader.Extensions[extension.name]) {
  102138. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  102139. return;
  102140. }
  102141. GLTFLoader.Extensions[extension.name] = extension;
  102142. };
  102143. GLTFLoader.prototype.dispose = function () { };
  102144. // #endregion
  102145. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  102146. var _this = this;
  102147. scene.useRightHandedSystem = true;
  102148. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102149. gltfRuntime.importOnlyMeshes = true;
  102150. if (meshesNames === "") {
  102151. gltfRuntime.importMeshesNames = [];
  102152. }
  102153. else if (typeof meshesNames === "string") {
  102154. gltfRuntime.importMeshesNames = [meshesNames];
  102155. }
  102156. else if (meshesNames && !(meshesNames instanceof Array)) {
  102157. gltfRuntime.importMeshesNames = [meshesNames];
  102158. }
  102159. else {
  102160. gltfRuntime.importMeshesNames = [];
  102161. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  102162. }
  102163. // Create nodes
  102164. _this._createNodes(gltfRuntime);
  102165. var meshes = new Array();
  102166. var skeletons = new Array();
  102167. // Fill arrays of meshes and skeletons
  102168. for (var nde in gltfRuntime.nodes) {
  102169. var node = gltfRuntime.nodes[nde];
  102170. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  102171. meshes.push(node.babylonNode);
  102172. }
  102173. }
  102174. for (var skl in gltfRuntime.skins) {
  102175. var skin = gltfRuntime.skins[skl];
  102176. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  102177. skeletons.push(skin.babylonSkeleton);
  102178. }
  102179. }
  102180. // Load buffers, shaders, materials, etc.
  102181. _this._loadBuffersAsync(gltfRuntime, function () {
  102182. _this._loadShadersAsync(gltfRuntime, function () {
  102183. importMaterials(gltfRuntime);
  102184. postLoad(gltfRuntime);
  102185. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102186. onSuccess(meshes, skeletons);
  102187. }
  102188. });
  102189. }, onProgress);
  102190. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102191. onSuccess(meshes, skeletons);
  102192. }
  102193. }, onError);
  102194. return true;
  102195. };
  102196. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102197. var _this = this;
  102198. return new Promise(function (resolve, reject) {
  102199. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  102200. resolve({
  102201. meshes: meshes,
  102202. particleSystems: [],
  102203. skeletons: skeletons,
  102204. animationGroups: []
  102205. });
  102206. }, onProgress, function (message) {
  102207. reject(new Error(message));
  102208. });
  102209. });
  102210. };
  102211. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  102212. var _this = this;
  102213. scene.useRightHandedSystem = true;
  102214. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102215. // Load runtime extensios
  102216. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  102217. // Create nodes
  102218. _this._createNodes(gltfRuntime);
  102219. // Load buffers, shaders, materials, etc.
  102220. _this._loadBuffersAsync(gltfRuntime, function () {
  102221. _this._loadShadersAsync(gltfRuntime, function () {
  102222. importMaterials(gltfRuntime);
  102223. postLoad(gltfRuntime);
  102224. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  102225. onSuccess();
  102226. }
  102227. });
  102228. });
  102229. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  102230. onSuccess();
  102231. }
  102232. }, onError);
  102233. }, onError);
  102234. };
  102235. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102236. var _this = this;
  102237. return new Promise(function (resolve, reject) {
  102238. _this._loadAsync(scene, data, rootUrl, function () {
  102239. resolve();
  102240. }, onProgress, function (message) {
  102241. reject(new Error(message));
  102242. });
  102243. });
  102244. };
  102245. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  102246. var hasShaders = false;
  102247. var processShader = function (sha, shader) {
  102248. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  102249. if (shaderString instanceof ArrayBuffer) {
  102250. return;
  102251. }
  102252. gltfRuntime.loadedShaderCount++;
  102253. if (shaderString) {
  102254. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  102255. }
  102256. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  102257. onload();
  102258. }
  102259. }, function () {
  102260. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  102261. });
  102262. };
  102263. for (var sha in gltfRuntime.shaders) {
  102264. hasShaders = true;
  102265. var shader = gltfRuntime.shaders[sha];
  102266. if (shader) {
  102267. processShader.bind(this, sha, shader)();
  102268. }
  102269. else {
  102270. BABYLON.Tools.Error("No shader named: " + sha);
  102271. }
  102272. }
  102273. if (!hasShaders) {
  102274. onload();
  102275. }
  102276. };
  102277. ;
  102278. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  102279. var hasBuffers = false;
  102280. var processBuffer = function (buf, buffer) {
  102281. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  102282. gltfRuntime.loadedBufferCount++;
  102283. if (bufferView) {
  102284. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  102285. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  102286. }
  102287. gltfRuntime.loadedBufferViews[buf] = bufferView;
  102288. }
  102289. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  102290. onLoad();
  102291. }
  102292. }, function () {
  102293. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  102294. });
  102295. };
  102296. for (var buf in gltfRuntime.buffers) {
  102297. hasBuffers = true;
  102298. var buffer = gltfRuntime.buffers[buf];
  102299. if (buffer) {
  102300. processBuffer.bind(this, buf, buffer)();
  102301. }
  102302. else {
  102303. BABYLON.Tools.Error("No buffer named: " + buf);
  102304. }
  102305. }
  102306. if (!hasBuffers) {
  102307. onLoad();
  102308. }
  102309. };
  102310. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  102311. var currentScene = gltfRuntime.currentScene;
  102312. if (currentScene) {
  102313. // Only one scene even if multiple scenes are defined
  102314. for (var i = 0; i < currentScene.nodes.length; i++) {
  102315. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102316. }
  102317. }
  102318. else {
  102319. // Load all scenes
  102320. for (var thing in gltfRuntime.scenes) {
  102321. currentScene = gltfRuntime.scenes[thing];
  102322. for (var i = 0; i < currentScene.nodes.length; i++) {
  102323. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102324. }
  102325. }
  102326. }
  102327. };
  102328. GLTFLoader.Extensions = {};
  102329. return GLTFLoader;
  102330. }());
  102331. GLTF1.GLTFLoader = GLTFLoader;
  102332. ;
  102333. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  102334. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102335. })(BABYLON || (BABYLON = {}));
  102336. //# sourceMappingURL=babylon.glTFLoader.js.map
  102337. var BABYLON;
  102338. (function (BABYLON) {
  102339. var GLTF1;
  102340. (function (GLTF1) {
  102341. /**
  102342. * Utils functions for GLTF
  102343. */
  102344. var GLTFUtils = /** @class */ (function () {
  102345. function GLTFUtils() {
  102346. }
  102347. /**
  102348. * Sets the given "parameter" matrix
  102349. * @param scene: the {BABYLON.Scene} object
  102350. * @param source: the source node where to pick the matrix
  102351. * @param parameter: the GLTF technique parameter
  102352. * @param uniformName: the name of the shader's uniform
  102353. * @param shaderMaterial: the shader material
  102354. */
  102355. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  102356. var mat = null;
  102357. if (parameter.semantic === "MODEL") {
  102358. mat = source.getWorldMatrix();
  102359. }
  102360. else if (parameter.semantic === "PROJECTION") {
  102361. mat = scene.getProjectionMatrix();
  102362. }
  102363. else if (parameter.semantic === "VIEW") {
  102364. mat = scene.getViewMatrix();
  102365. }
  102366. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  102367. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  102368. }
  102369. else if (parameter.semantic === "MODELVIEW") {
  102370. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  102371. }
  102372. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  102373. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  102374. }
  102375. else if (parameter.semantic === "MODELINVERSE") {
  102376. mat = source.getWorldMatrix().invert();
  102377. }
  102378. else if (parameter.semantic === "VIEWINVERSE") {
  102379. mat = scene.getViewMatrix().invert();
  102380. }
  102381. else if (parameter.semantic === "PROJECTIONINVERSE") {
  102382. mat = scene.getProjectionMatrix().invert();
  102383. }
  102384. else if (parameter.semantic === "MODELVIEWINVERSE") {
  102385. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  102386. }
  102387. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  102388. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  102389. }
  102390. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  102391. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  102392. }
  102393. else {
  102394. debugger;
  102395. }
  102396. if (mat) {
  102397. switch (parameter.type) {
  102398. case GLTF1.EParameterType.FLOAT_MAT2:
  102399. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  102400. break;
  102401. case GLTF1.EParameterType.FLOAT_MAT3:
  102402. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  102403. break;
  102404. case GLTF1.EParameterType.FLOAT_MAT4:
  102405. shaderMaterial.setMatrix(uniformName, mat);
  102406. break;
  102407. default: break;
  102408. }
  102409. }
  102410. };
  102411. /**
  102412. * Sets the given "parameter" matrix
  102413. * @param shaderMaterial: the shader material
  102414. * @param uniform: the name of the shader's uniform
  102415. * @param value: the value of the uniform
  102416. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  102417. */
  102418. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  102419. switch (type) {
  102420. case GLTF1.EParameterType.FLOAT:
  102421. shaderMaterial.setFloat(uniform, value);
  102422. return true;
  102423. case GLTF1.EParameterType.FLOAT_VEC2:
  102424. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  102425. return true;
  102426. case GLTF1.EParameterType.FLOAT_VEC3:
  102427. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  102428. return true;
  102429. case GLTF1.EParameterType.FLOAT_VEC4:
  102430. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  102431. return true;
  102432. default: return false;
  102433. }
  102434. };
  102435. /**
  102436. * Returns the wrap mode of the texture
  102437. * @param mode: the mode value
  102438. */
  102439. GLTFUtils.GetWrapMode = function (mode) {
  102440. switch (mode) {
  102441. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  102442. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  102443. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102444. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102445. }
  102446. };
  102447. /**
  102448. * Returns the byte stride giving an accessor
  102449. * @param accessor: the GLTF accessor objet
  102450. */
  102451. GLTFUtils.GetByteStrideFromType = function (accessor) {
  102452. // Needs this function since "byteStride" isn't requiered in glTF format
  102453. var type = accessor.type;
  102454. switch (type) {
  102455. case "VEC2": return 2;
  102456. case "VEC3": return 3;
  102457. case "VEC4": return 4;
  102458. case "MAT2": return 4;
  102459. case "MAT3": return 9;
  102460. case "MAT4": return 16;
  102461. default: return 1;
  102462. }
  102463. };
  102464. /**
  102465. * Returns the texture filter mode giving a mode value
  102466. * @param mode: the filter mode value
  102467. */
  102468. GLTFUtils.GetTextureFilterMode = function (mode) {
  102469. switch (mode) {
  102470. case GLTF1.ETextureFilterType.LINEAR:
  102471. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  102472. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102473. case GLTF1.ETextureFilterType.NEAREST:
  102474. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  102475. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102476. }
  102477. };
  102478. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  102479. var byteOffset = bufferView.byteOffset + byteOffset;
  102480. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  102481. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  102482. throw new Error("Buffer access is out of range");
  102483. }
  102484. var buffer = loadedBufferView.buffer;
  102485. byteOffset += loadedBufferView.byteOffset;
  102486. switch (componentType) {
  102487. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  102488. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  102489. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  102490. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  102491. default: return new Float32Array(buffer, byteOffset, byteLength);
  102492. }
  102493. };
  102494. /**
  102495. * Returns a buffer from its accessor
  102496. * @param gltfRuntime: the GLTF runtime
  102497. * @param accessor: the GLTF accessor
  102498. */
  102499. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  102500. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  102501. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  102502. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  102503. };
  102504. /**
  102505. * Decodes a buffer view into a string
  102506. * @param view: the buffer view
  102507. */
  102508. GLTFUtils.DecodeBufferToText = function (view) {
  102509. var result = "";
  102510. var length = view.byteLength;
  102511. for (var i = 0; i < length; ++i) {
  102512. result += String.fromCharCode(view[i]);
  102513. }
  102514. return result;
  102515. };
  102516. /**
  102517. * Returns the default material of gltf. Related to
  102518. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  102519. * @param scene: the Babylon.js scene
  102520. */
  102521. GLTFUtils.GetDefaultMaterial = function (scene) {
  102522. if (!GLTFUtils._DefaultMaterial) {
  102523. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  102524. "precision highp float;",
  102525. "",
  102526. "uniform mat4 worldView;",
  102527. "uniform mat4 projection;",
  102528. "",
  102529. "attribute vec3 position;",
  102530. "",
  102531. "void main(void)",
  102532. "{",
  102533. " gl_Position = projection * worldView * vec4(position, 1.0);",
  102534. "}"
  102535. ].join("\n");
  102536. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  102537. "precision highp float;",
  102538. "",
  102539. "uniform vec4 u_emission;",
  102540. "",
  102541. "void main(void)",
  102542. "{",
  102543. " gl_FragColor = u_emission;",
  102544. "}"
  102545. ].join("\n");
  102546. var shaderPath = {
  102547. vertex: "GLTFDefaultMaterial",
  102548. fragment: "GLTFDefaultMaterial"
  102549. };
  102550. var options = {
  102551. attributes: ["position"],
  102552. uniforms: ["worldView", "projection", "u_emission"],
  102553. samplers: new Array(),
  102554. needAlphaBlending: false
  102555. };
  102556. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  102557. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  102558. }
  102559. return GLTFUtils._DefaultMaterial;
  102560. };
  102561. // The GLTF default material
  102562. GLTFUtils._DefaultMaterial = null;
  102563. return GLTFUtils;
  102564. }());
  102565. GLTF1.GLTFUtils = GLTFUtils;
  102566. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102567. })(BABYLON || (BABYLON = {}));
  102568. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  102569. var BABYLON;
  102570. (function (BABYLON) {
  102571. var GLTF1;
  102572. (function (GLTF1) {
  102573. var GLTFLoaderExtension = /** @class */ (function () {
  102574. function GLTFLoaderExtension(name) {
  102575. this._name = name;
  102576. }
  102577. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  102578. get: function () {
  102579. return this._name;
  102580. },
  102581. enumerable: true,
  102582. configurable: true
  102583. });
  102584. /**
  102585. * Defines an override for loading the runtime
  102586. * Return true to stop further extensions from loading the runtime
  102587. */
  102588. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102589. return false;
  102590. };
  102591. /**
  102592. * Defines an onverride for creating gltf runtime
  102593. * Return true to stop further extensions from creating the runtime
  102594. */
  102595. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102596. return false;
  102597. };
  102598. /**
  102599. * Defines an override for loading buffers
  102600. * Return true to stop further extensions from loading this buffer
  102601. */
  102602. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102603. return false;
  102604. };
  102605. /**
  102606. * Defines an override for loading texture buffers
  102607. * Return true to stop further extensions from loading this texture data
  102608. */
  102609. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102610. return false;
  102611. };
  102612. /**
  102613. * Defines an override for creating textures
  102614. * Return true to stop further extensions from loading this texture
  102615. */
  102616. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102617. return false;
  102618. };
  102619. /**
  102620. * Defines an override for loading shader strings
  102621. * Return true to stop further extensions from loading this shader data
  102622. */
  102623. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102624. return false;
  102625. };
  102626. /**
  102627. * Defines an override for loading materials
  102628. * Return true to stop further extensions from loading this material
  102629. */
  102630. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102631. return false;
  102632. };
  102633. // ---------
  102634. // Utilities
  102635. // ---------
  102636. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102637. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102638. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  102639. }, function () {
  102640. setTimeout(function () {
  102641. if (!onSuccess) {
  102642. return;
  102643. }
  102644. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  102645. });
  102646. });
  102647. };
  102648. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102649. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102650. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  102651. }, function () {
  102652. setTimeout(function () {
  102653. onSuccess();
  102654. });
  102655. });
  102656. };
  102657. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102658. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102659. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  102660. }, function () {
  102661. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  102662. });
  102663. };
  102664. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  102665. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  102666. if (buffer) {
  102667. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102668. }
  102669. }, onError);
  102670. };
  102671. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102672. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102673. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  102674. }, function () {
  102675. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  102676. });
  102677. };
  102678. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102679. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102680. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  102681. }, function () {
  102682. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  102683. });
  102684. };
  102685. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102686. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102687. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  102688. }, function () {
  102689. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  102690. });
  102691. };
  102692. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102693. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102694. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102695. }, function () {
  102696. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102697. });
  102698. };
  102699. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  102700. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  102701. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  102702. if (func(loaderExtension)) {
  102703. return;
  102704. }
  102705. }
  102706. defaultFunc();
  102707. };
  102708. return GLTFLoaderExtension;
  102709. }());
  102710. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  102711. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102712. })(BABYLON || (BABYLON = {}));
  102713. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  102714. var BABYLON;
  102715. (function (BABYLON) {
  102716. var GLTF1;
  102717. (function (GLTF1) {
  102718. var BinaryExtensionBufferName = "binary_glTF";
  102719. ;
  102720. ;
  102721. var GLTFBinaryExtension = /** @class */ (function (_super) {
  102722. __extends(GLTFBinaryExtension, _super);
  102723. function GLTFBinaryExtension() {
  102724. return _super.call(this, "KHR_binary_glTF") || this;
  102725. }
  102726. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102727. var extensionsUsed = data.json.extensionsUsed;
  102728. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  102729. return false;
  102730. }
  102731. this._bin = data.bin;
  102732. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  102733. return true;
  102734. };
  102735. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102736. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  102737. return false;
  102738. }
  102739. if (id !== BinaryExtensionBufferName) {
  102740. return false;
  102741. }
  102742. onSuccess(this._bin);
  102743. return true;
  102744. };
  102745. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102746. var texture = gltfRuntime.textures[id];
  102747. var source = gltfRuntime.images[texture.source];
  102748. if (!source.extensions || !(this.name in source.extensions)) {
  102749. return false;
  102750. }
  102751. var sourceExt = source.extensions[this.name];
  102752. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  102753. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  102754. onSuccess(buffer);
  102755. return true;
  102756. };
  102757. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102758. var shader = gltfRuntime.shaders[id];
  102759. if (!shader.extensions || !(this.name in shader.extensions)) {
  102760. return false;
  102761. }
  102762. var binaryExtensionShader = shader.extensions[this.name];
  102763. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  102764. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  102765. setTimeout(function () {
  102766. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  102767. onSuccess(shaderString);
  102768. });
  102769. return true;
  102770. };
  102771. return GLTFBinaryExtension;
  102772. }(GLTF1.GLTFLoaderExtension));
  102773. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  102774. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  102775. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102776. })(BABYLON || (BABYLON = {}));
  102777. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  102778. var BABYLON;
  102779. (function (BABYLON) {
  102780. var GLTF1;
  102781. (function (GLTF1) {
  102782. ;
  102783. ;
  102784. ;
  102785. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  102786. __extends(GLTFMaterialsCommonExtension, _super);
  102787. function GLTFMaterialsCommonExtension() {
  102788. return _super.call(this, "KHR_materials_common") || this;
  102789. }
  102790. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102791. if (!gltfRuntime.extensions)
  102792. return false;
  102793. var extension = gltfRuntime.extensions[this.name];
  102794. if (!extension)
  102795. return false;
  102796. // Create lights
  102797. var lights = extension.lights;
  102798. if (lights) {
  102799. for (var thing in lights) {
  102800. var light = lights[thing];
  102801. switch (light.type) {
  102802. case "ambient":
  102803. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  102804. var ambient = light.ambient;
  102805. if (ambient) {
  102806. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  102807. }
  102808. break;
  102809. case "point":
  102810. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  102811. var point = light.point;
  102812. if (point) {
  102813. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  102814. }
  102815. break;
  102816. case "directional":
  102817. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  102818. var directional = light.directional;
  102819. if (directional) {
  102820. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  102821. }
  102822. break;
  102823. case "spot":
  102824. var spot = light.spot;
  102825. if (spot) {
  102826. 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);
  102827. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  102828. }
  102829. break;
  102830. default:
  102831. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  102832. break;
  102833. }
  102834. }
  102835. }
  102836. return false;
  102837. };
  102838. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102839. var material = gltfRuntime.materials[id];
  102840. if (!material || !material.extensions)
  102841. return false;
  102842. var extension = material.extensions[this.name];
  102843. if (!extension)
  102844. return false;
  102845. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102846. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102847. if (extension.technique === "CONSTANT") {
  102848. standardMaterial.disableLighting = true;
  102849. }
  102850. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  102851. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  102852. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  102853. // Ambient
  102854. if (typeof extension.values.ambient === "string") {
  102855. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  102856. }
  102857. else {
  102858. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  102859. }
  102860. // Diffuse
  102861. if (typeof extension.values.diffuse === "string") {
  102862. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  102863. }
  102864. else {
  102865. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  102866. }
  102867. // Emission
  102868. if (typeof extension.values.emission === "string") {
  102869. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  102870. }
  102871. else {
  102872. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  102873. }
  102874. // Specular
  102875. if (typeof extension.values.specular === "string") {
  102876. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  102877. }
  102878. else {
  102879. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  102880. }
  102881. return true;
  102882. };
  102883. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  102884. // Create buffer from texture url
  102885. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  102886. // Create texture from buffer
  102887. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  102888. }, onError);
  102889. };
  102890. return GLTFMaterialsCommonExtension;
  102891. }(GLTF1.GLTFLoaderExtension));
  102892. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  102893. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  102894. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102895. })(BABYLON || (BABYLON = {}));
  102896. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  102897. var BABYLON;
  102898. (function (BABYLON) {
  102899. var GLTF2;
  102900. (function (GLTF2) {
  102901. var ArrayItem = /** @class */ (function () {
  102902. function ArrayItem() {
  102903. }
  102904. ArrayItem.Assign = function (values) {
  102905. if (values) {
  102906. for (var index = 0; index < values.length; index++) {
  102907. values[index]._index = index;
  102908. }
  102909. }
  102910. };
  102911. return ArrayItem;
  102912. }());
  102913. GLTF2.ArrayItem = ArrayItem;
  102914. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102915. })(BABYLON || (BABYLON = {}));
  102916. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  102917. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  102918. var BABYLON;
  102919. (function (BABYLON) {
  102920. var GLTF2;
  102921. (function (GLTF2) {
  102922. var GLTFLoader = /** @class */ (function () {
  102923. function GLTFLoader() {
  102924. this._completePromises = new Array();
  102925. this._disposed = false;
  102926. this._state = null;
  102927. this._extensions = {};
  102928. this._defaultSampler = {};
  102929. this._defaultBabylonMaterials = {};
  102930. this._requests = new Array();
  102931. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  102932. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  102933. this.compileMaterials = false;
  102934. this.useClipPlane = false;
  102935. this.compileShadowGenerators = false;
  102936. this.onDisposeObservable = new BABYLON.Observable();
  102937. this.onMeshLoadedObservable = new BABYLON.Observable();
  102938. this.onTextureLoadedObservable = new BABYLON.Observable();
  102939. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102940. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102941. this.onCompleteObservable = new BABYLON.Observable();
  102942. }
  102943. GLTFLoader._Register = function (name, factory) {
  102944. if (GLTFLoader._Factories[name]) {
  102945. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  102946. return;
  102947. }
  102948. GLTFLoader._Factories[name] = factory;
  102949. // Keep the order of registration so that extensions registered first are called first.
  102950. GLTFLoader._Names.push(name);
  102951. };
  102952. Object.defineProperty(GLTFLoader.prototype, "state", {
  102953. get: function () {
  102954. return this._state;
  102955. },
  102956. enumerable: true,
  102957. configurable: true
  102958. });
  102959. GLTFLoader.prototype.dispose = function () {
  102960. if (this._disposed) {
  102961. return;
  102962. }
  102963. this._disposed = true;
  102964. this.onDisposeObservable.notifyObservers(this);
  102965. this.onDisposeObservable.clear();
  102966. this._clear();
  102967. };
  102968. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102969. var _this = this;
  102970. return Promise.resolve().then(function () {
  102971. var nodes = null;
  102972. if (meshesNames) {
  102973. var nodeMap_1 = {};
  102974. if (_this._gltf.nodes) {
  102975. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  102976. var node = _a[_i];
  102977. if (node.name) {
  102978. nodeMap_1[node.name] = node;
  102979. }
  102980. }
  102981. }
  102982. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  102983. nodes = names.map(function (name) {
  102984. var node = nodeMap_1[name];
  102985. if (!node) {
  102986. throw new Error("Failed to find node '" + name + "'");
  102987. }
  102988. return node;
  102989. });
  102990. }
  102991. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  102992. return {
  102993. meshes: _this._getMeshes(),
  102994. particleSystems: [],
  102995. skeletons: _this._getSkeletons(),
  102996. animationGroups: _this._getAnimationGroups()
  102997. };
  102998. });
  102999. });
  103000. };
  103001. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103002. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  103003. };
  103004. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  103005. var _this = this;
  103006. return Promise.resolve().then(function () {
  103007. _this._loadExtensions();
  103008. _this._babylonScene = scene;
  103009. _this._rootUrl = rootUrl;
  103010. _this._progressCallback = onProgress;
  103011. _this._state = BABYLON.GLTFLoaderState.LOADING;
  103012. _this._loadData(data);
  103013. _this._checkExtensions();
  103014. var promises = new Array();
  103015. if (nodes) {
  103016. promises.push(_this._loadNodesAsync(nodes));
  103017. }
  103018. else {
  103019. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  103020. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  103021. }
  103022. if (_this.compileMaterials) {
  103023. promises.push(_this._compileMaterialsAsync());
  103024. }
  103025. if (_this.compileShadowGenerators) {
  103026. promises.push(_this._compileShadowGeneratorsAsync());
  103027. }
  103028. var resultPromise = Promise.all(promises).then(function () {
  103029. _this._state = BABYLON.GLTFLoaderState.READY;
  103030. _this._startAnimations();
  103031. });
  103032. resultPromise.then(function () {
  103033. _this._rootBabylonMesh.setEnabled(true);
  103034. BABYLON.Tools.SetImmediate(function () {
  103035. if (!_this._disposed) {
  103036. Promise.all(_this._completePromises).then(function () {
  103037. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  103038. _this.onCompleteObservable.notifyObservers(_this);
  103039. _this.onCompleteObservable.clear();
  103040. _this._clear();
  103041. }).catch(function (error) {
  103042. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103043. _this._clear();
  103044. });
  103045. }
  103046. });
  103047. });
  103048. return resultPromise;
  103049. }).catch(function (error) {
  103050. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103051. _this._clear();
  103052. throw error;
  103053. });
  103054. };
  103055. GLTFLoader.prototype._loadExtensions = function () {
  103056. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  103057. var name_1 = _a[_i];
  103058. var extension = GLTFLoader._Factories[name_1](this);
  103059. this._extensions[name_1] = extension;
  103060. this.onExtensionLoadedObservable.notifyObservers(extension);
  103061. }
  103062. this.onExtensionLoadedObservable.clear();
  103063. };
  103064. GLTFLoader.prototype._loadData = function (data) {
  103065. this._gltf = data.json;
  103066. this._setupData();
  103067. if (data.bin) {
  103068. var buffers = this._gltf.buffers;
  103069. if (buffers && buffers[0] && !buffers[0].uri) {
  103070. var binaryBuffer = buffers[0];
  103071. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  103072. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  103073. }
  103074. binaryBuffer._data = Promise.resolve(data.bin);
  103075. }
  103076. else {
  103077. BABYLON.Tools.Warn("Unexpected BIN chunk");
  103078. }
  103079. }
  103080. };
  103081. GLTFLoader.prototype._setupData = function () {
  103082. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  103083. GLTF2.ArrayItem.Assign(this._gltf.animations);
  103084. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  103085. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  103086. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  103087. GLTF2.ArrayItem.Assign(this._gltf.images);
  103088. GLTF2.ArrayItem.Assign(this._gltf.materials);
  103089. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  103090. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  103091. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  103092. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  103093. GLTF2.ArrayItem.Assign(this._gltf.skins);
  103094. GLTF2.ArrayItem.Assign(this._gltf.textures);
  103095. if (this._gltf.nodes) {
  103096. var nodeParents = {};
  103097. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  103098. var node = _a[_i];
  103099. if (node.children) {
  103100. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  103101. var index = _c[_b];
  103102. nodeParents[index] = node._index;
  103103. }
  103104. }
  103105. }
  103106. var rootNode = this._createRootNode();
  103107. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  103108. var node = _e[_d];
  103109. var parentIndex = nodeParents[node._index];
  103110. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  103111. }
  103112. }
  103113. };
  103114. GLTFLoader.prototype._checkExtensions = function () {
  103115. if (this._gltf.extensionsRequired) {
  103116. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  103117. var name_2 = _a[_i];
  103118. var extension = this._extensions[name_2];
  103119. if (!extension || !extension.enabled) {
  103120. throw new Error("Require extension " + name_2 + " is not available");
  103121. }
  103122. }
  103123. }
  103124. };
  103125. GLTFLoader.prototype._createRootNode = function () {
  103126. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  103127. this._rootBabylonMesh.setEnabled(false);
  103128. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  103129. switch (this.coordinateSystemMode) {
  103130. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  103131. if (!this._babylonScene.useRightHandedSystem) {
  103132. rootNode.rotation = [0, 1, 0, 0];
  103133. rootNode.scale = [1, 1, -1];
  103134. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  103135. }
  103136. break;
  103137. }
  103138. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  103139. this._babylonScene.useRightHandedSystem = true;
  103140. break;
  103141. }
  103142. default: {
  103143. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  103144. }
  103145. }
  103146. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  103147. return rootNode;
  103148. };
  103149. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  103150. var promises = new Array();
  103151. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  103152. var node = nodes_1[_i];
  103153. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103154. }
  103155. promises.push(this._loadAnimationsAsync());
  103156. return Promise.all(promises).then(function () { });
  103157. };
  103158. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  103159. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  103160. if (promise) {
  103161. return promise;
  103162. }
  103163. var promises = new Array();
  103164. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  103165. var index = _a[_i];
  103166. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  103167. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103168. }
  103169. promises.push(this._loadAnimationsAsync());
  103170. return Promise.all(promises).then(function () { });
  103171. };
  103172. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  103173. if (node._primitiveBabylonMeshes) {
  103174. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  103175. var babylonMesh = _a[_i];
  103176. callback(babylonMesh);
  103177. }
  103178. }
  103179. else {
  103180. callback(node._babylonMesh);
  103181. }
  103182. };
  103183. GLTFLoader.prototype._getMeshes = function () {
  103184. var meshes = new Array();
  103185. // Root mesh is always first.
  103186. meshes.push(this._rootBabylonMesh);
  103187. var nodes = this._gltf.nodes;
  103188. if (nodes) {
  103189. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  103190. var node = nodes_2[_i];
  103191. if (node._babylonMesh) {
  103192. meshes.push(node._babylonMesh);
  103193. }
  103194. if (node._primitiveBabylonMeshes) {
  103195. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  103196. var babylonMesh = _b[_a];
  103197. meshes.push(babylonMesh);
  103198. }
  103199. }
  103200. }
  103201. }
  103202. return meshes;
  103203. };
  103204. GLTFLoader.prototype._getSkeletons = function () {
  103205. var skeletons = new Array();
  103206. var skins = this._gltf.skins;
  103207. if (skins) {
  103208. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  103209. var skin = skins_1[_i];
  103210. if (skin._babylonSkeleton) {
  103211. skeletons.push(skin._babylonSkeleton);
  103212. }
  103213. }
  103214. }
  103215. return skeletons;
  103216. };
  103217. GLTFLoader.prototype._getAnimationGroups = function () {
  103218. var animationGroups = new Array();
  103219. var animations = this._gltf.animations;
  103220. if (animations) {
  103221. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103222. var animation = animations_1[_i];
  103223. if (animation._babylonAnimationGroup) {
  103224. animationGroups.push(animation._babylonAnimationGroup);
  103225. }
  103226. }
  103227. }
  103228. return animationGroups;
  103229. };
  103230. GLTFLoader.prototype._startAnimations = function () {
  103231. switch (this.animationStartMode) {
  103232. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  103233. // do nothing
  103234. break;
  103235. }
  103236. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  103237. var babylonAnimationGroups = this._getAnimationGroups();
  103238. if (babylonAnimationGroups.length !== 0) {
  103239. babylonAnimationGroups[0].start(true);
  103240. }
  103241. break;
  103242. }
  103243. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  103244. var babylonAnimationGroups = this._getAnimationGroups();
  103245. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  103246. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  103247. babylonAnimationGroup.start(true);
  103248. }
  103249. break;
  103250. }
  103251. default: {
  103252. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  103253. return;
  103254. }
  103255. }
  103256. };
  103257. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  103258. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  103259. if (promise) {
  103260. return promise;
  103261. }
  103262. if (node._babylonMesh) {
  103263. throw new Error(context + ": Invalid recursive node hierarchy");
  103264. }
  103265. var promises = new Array();
  103266. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  103267. node._babylonMesh = babylonMesh;
  103268. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103269. node._babylonAnimationTargets.push(babylonMesh);
  103270. GLTFLoader._LoadTransform(node, babylonMesh);
  103271. if (node.mesh != undefined) {
  103272. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  103273. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  103274. }
  103275. if (node.children) {
  103276. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  103277. var index = _a[_i];
  103278. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  103279. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  103280. }
  103281. }
  103282. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103283. return Promise.all(promises).then(function () { });
  103284. };
  103285. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  103286. // TODO: instancing
  103287. var _this = this;
  103288. var promises = new Array();
  103289. var primitives = mesh.primitives;
  103290. if (!primitives || primitives.length === 0) {
  103291. throw new Error(context + ": Primitives are missing");
  103292. }
  103293. GLTF2.ArrayItem.Assign(primitives);
  103294. if (primitives.length === 1) {
  103295. var primitive = primitives[0];
  103296. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  103297. }
  103298. else {
  103299. node._primitiveBabylonMeshes = [];
  103300. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  103301. var primitive = primitives_1[_i];
  103302. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  103303. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  103304. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  103305. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103306. }
  103307. }
  103308. if (node.skin != undefined) {
  103309. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  103310. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  103311. }
  103312. return Promise.all(promises).then(function () {
  103313. _this._forEachPrimitive(node, function (babylonMesh) {
  103314. babylonMesh._refreshBoundingInfo(true);
  103315. });
  103316. });
  103317. };
  103318. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  103319. var _this = this;
  103320. var promises = new Array();
  103321. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  103322. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  103323. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  103324. babylonGeometry.applyToMesh(babylonMesh);
  103325. });
  103326. }));
  103327. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  103328. if (primitive.material == undefined) {
  103329. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  103330. }
  103331. else {
  103332. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  103333. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  103334. babylonMesh.material = babylonMaterial;
  103335. }));
  103336. }
  103337. return Promise.all(promises).then(function () { });
  103338. };
  103339. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  103340. var _this = this;
  103341. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  103342. if (promise) {
  103343. return promise;
  103344. }
  103345. var attributes = primitive.attributes;
  103346. if (!attributes) {
  103347. throw new Error(context + ": Attributes are missing");
  103348. }
  103349. var promises = new Array();
  103350. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  103351. if (primitive.indices == undefined) {
  103352. babylonMesh.isUnIndexed = true;
  103353. }
  103354. else {
  103355. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  103356. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103357. babylonGeometry.setIndices(data);
  103358. }));
  103359. }
  103360. var loadAttribute = function (attribute, kind, callback) {
  103361. if (attributes[attribute] == undefined) {
  103362. return;
  103363. }
  103364. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  103365. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  103366. babylonMesh._delayInfo.push(kind);
  103367. }
  103368. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103369. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  103370. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  103371. }));
  103372. if (callback) {
  103373. callback(accessor);
  103374. }
  103375. };
  103376. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  103377. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  103378. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  103379. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  103380. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  103381. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  103382. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  103383. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  103384. if (accessor.type === "VEC4" /* VEC4 */) {
  103385. babylonMesh.hasVertexAlpha = true;
  103386. }
  103387. });
  103388. return Promise.all(promises).then(function () {
  103389. return babylonGeometry;
  103390. });
  103391. };
  103392. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  103393. if (!primitive.targets) {
  103394. return;
  103395. }
  103396. if (node._numMorphTargets == undefined) {
  103397. node._numMorphTargets = primitive.targets.length;
  103398. }
  103399. else if (primitive.targets.length !== node._numMorphTargets) {
  103400. throw new Error(context + ": Primitives do not have the same number of targets");
  103401. }
  103402. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  103403. for (var index = 0; index < primitive.targets.length; index++) {
  103404. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  103405. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  103406. // TODO: tell the target whether it has positions, normals, tangents
  103407. }
  103408. };
  103409. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  103410. if (!primitive.targets) {
  103411. return Promise.resolve();
  103412. }
  103413. var promises = new Array();
  103414. var morphTargetManager = babylonMesh.morphTargetManager;
  103415. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  103416. var babylonMorphTarget = morphTargetManager.getTarget(index);
  103417. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  103418. }
  103419. return Promise.all(promises).then(function () { });
  103420. };
  103421. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  103422. var _this = this;
  103423. var promises = new Array();
  103424. var loadAttribute = function (attribute, kind, setData) {
  103425. if (attributes[attribute] == undefined) {
  103426. return;
  103427. }
  103428. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  103429. if (!babylonVertexBuffer) {
  103430. return;
  103431. }
  103432. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103433. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103434. if (!(data instanceof Float32Array)) {
  103435. throw new Error(context + ": Morph target accessor must have float data");
  103436. }
  103437. setData(babylonVertexBuffer, data);
  103438. }));
  103439. };
  103440. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  103441. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103442. data[index] += value;
  103443. });
  103444. babylonMorphTarget.setPositions(data);
  103445. });
  103446. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  103447. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103448. data[index] += value;
  103449. });
  103450. babylonMorphTarget.setNormals(data);
  103451. });
  103452. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  103453. var dataIndex = 0;
  103454. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103455. // Tangent data for morph targets is stored as xyz delta.
  103456. // The vertexData.tangent is stored as xyzw.
  103457. // So we need to skip every fourth vertexData.tangent.
  103458. if (((index + 1) % 4) !== 0) {
  103459. data[dataIndex++] += value;
  103460. }
  103461. });
  103462. babylonMorphTarget.setTangents(data);
  103463. });
  103464. return Promise.all(promises).then(function () { });
  103465. };
  103466. GLTFLoader._LoadTransform = function (node, babylonNode) {
  103467. var position = BABYLON.Vector3.Zero();
  103468. var rotation = BABYLON.Quaternion.Identity();
  103469. var scaling = BABYLON.Vector3.One();
  103470. if (node.matrix) {
  103471. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  103472. matrix.decompose(scaling, rotation, position);
  103473. }
  103474. else {
  103475. if (node.translation)
  103476. position = BABYLON.Vector3.FromArray(node.translation);
  103477. if (node.rotation)
  103478. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  103479. if (node.scale)
  103480. scaling = BABYLON.Vector3.FromArray(node.scale);
  103481. }
  103482. babylonNode.position = position;
  103483. babylonNode.rotationQuaternion = rotation;
  103484. babylonNode.scaling = scaling;
  103485. };
  103486. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  103487. var _this = this;
  103488. var assignSkeleton = function () {
  103489. _this._forEachPrimitive(node, function (babylonMesh) {
  103490. babylonMesh.skeleton = skin._babylonSkeleton;
  103491. });
  103492. // Ignore the TRS of skinned nodes.
  103493. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  103494. node._babylonMesh.parent = _this._rootBabylonMesh;
  103495. node._babylonMesh.position = BABYLON.Vector3.Zero();
  103496. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  103497. node._babylonMesh.scaling = BABYLON.Vector3.One();
  103498. };
  103499. if (skin._loaded) {
  103500. return skin._loaded.then(function () {
  103501. assignSkeleton();
  103502. });
  103503. }
  103504. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  103505. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  103506. var skeletonId = "skeleton" + skin._index;
  103507. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  103508. skin._babylonSkeleton = babylonSkeleton;
  103509. _this._loadBones(context, skin, inverseBindMatricesData);
  103510. assignSkeleton();
  103511. }));
  103512. };
  103513. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  103514. if (skin.inverseBindMatrices == undefined) {
  103515. return Promise.resolve(null);
  103516. }
  103517. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  103518. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103519. return data;
  103520. });
  103521. };
  103522. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  103523. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  103524. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103525. node._babylonAnimationTargets.push(babylonBone);
  103526. return babylonBone;
  103527. };
  103528. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  103529. var babylonBones = {};
  103530. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  103531. var index = _a[_i];
  103532. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  103533. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  103534. }
  103535. };
  103536. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  103537. var babylonBone = babylonBones[node._index];
  103538. if (babylonBone) {
  103539. return babylonBone;
  103540. }
  103541. var boneIndex = skin.joints.indexOf(node._index);
  103542. var baseMatrix = BABYLON.Matrix.Identity();
  103543. if (inverseBindMatricesData && boneIndex !== -1) {
  103544. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  103545. baseMatrix.invertToRef(baseMatrix);
  103546. }
  103547. var babylonParentBone = null;
  103548. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  103549. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  103550. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  103551. }
  103552. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  103553. babylonBones[node._index] = babylonBone;
  103554. return babylonBone;
  103555. };
  103556. GLTFLoader.prototype._getNodeMatrix = function (node) {
  103557. return node.matrix ?
  103558. BABYLON.Matrix.FromArray(node.matrix) :
  103559. 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());
  103560. };
  103561. GLTFLoader.prototype._loadAnimationsAsync = function () {
  103562. var animations = this._gltf.animations;
  103563. if (!animations) {
  103564. return Promise.resolve();
  103565. }
  103566. var promises = new Array();
  103567. for (var index = 0; index < animations.length; index++) {
  103568. var animation = animations[index];
  103569. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  103570. }
  103571. return Promise.all(promises).then(function () { });
  103572. };
  103573. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  103574. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  103575. animation._babylonAnimationGroup = babylonAnimationGroup;
  103576. var promises = new Array();
  103577. GLTF2.ArrayItem.Assign(animation.channels);
  103578. GLTF2.ArrayItem.Assign(animation.samplers);
  103579. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  103580. var channel = _a[_i];
  103581. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  103582. }
  103583. return Promise.all(promises).then(function () {
  103584. babylonAnimationGroup.normalize();
  103585. });
  103586. };
  103587. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  103588. var _this = this;
  103589. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  103590. if (!targetNode._babylonMesh) {
  103591. return Promise.resolve();
  103592. }
  103593. // Ignore animations targeting TRS of skinned nodes.
  103594. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  103595. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  103596. return Promise.resolve();
  103597. }
  103598. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  103599. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  103600. var targetPath;
  103601. var animationType;
  103602. switch (channel.target.path) {
  103603. case "translation" /* TRANSLATION */: {
  103604. targetPath = "position";
  103605. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103606. break;
  103607. }
  103608. case "rotation" /* ROTATION */: {
  103609. targetPath = "rotationQuaternion";
  103610. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  103611. break;
  103612. }
  103613. case "scale" /* SCALE */: {
  103614. targetPath = "scaling";
  103615. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103616. break;
  103617. }
  103618. case "weights" /* WEIGHTS */: {
  103619. targetPath = "influence";
  103620. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  103621. break;
  103622. }
  103623. default: {
  103624. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  103625. }
  103626. }
  103627. var outputBufferOffset = 0;
  103628. var getNextOutputValue;
  103629. switch (targetPath) {
  103630. case "position": {
  103631. getNextOutputValue = function () {
  103632. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  103633. outputBufferOffset += 3;
  103634. return value;
  103635. };
  103636. break;
  103637. }
  103638. case "rotationQuaternion": {
  103639. getNextOutputValue = function () {
  103640. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  103641. outputBufferOffset += 4;
  103642. return value;
  103643. };
  103644. break;
  103645. }
  103646. case "scaling": {
  103647. getNextOutputValue = function () {
  103648. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  103649. outputBufferOffset += 3;
  103650. return value;
  103651. };
  103652. break;
  103653. }
  103654. case "influence": {
  103655. getNextOutputValue = function () {
  103656. var value = new Array(targetNode._numMorphTargets);
  103657. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  103658. value[i] = data.output[outputBufferOffset++];
  103659. }
  103660. return value;
  103661. };
  103662. break;
  103663. }
  103664. }
  103665. var getNextKey;
  103666. switch (data.interpolation) {
  103667. case "STEP" /* STEP */: {
  103668. getNextKey = function (frameIndex) { return ({
  103669. frame: data.input[frameIndex],
  103670. value: getNextOutputValue(),
  103671. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  103672. }); };
  103673. break;
  103674. }
  103675. case "LINEAR" /* LINEAR */: {
  103676. getNextKey = function (frameIndex) { return ({
  103677. frame: data.input[frameIndex],
  103678. value: getNextOutputValue()
  103679. }); };
  103680. break;
  103681. }
  103682. case "CUBICSPLINE" /* CUBICSPLINE */: {
  103683. getNextKey = function (frameIndex) { return ({
  103684. frame: data.input[frameIndex],
  103685. inTangent: getNextOutputValue(),
  103686. value: getNextOutputValue(),
  103687. outTangent: getNextOutputValue()
  103688. }); };
  103689. break;
  103690. }
  103691. }
  103692. var keys = new Array(data.input.length);
  103693. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  103694. keys[frameIndex] = getNextKey(frameIndex);
  103695. }
  103696. if (targetPath === "influence") {
  103697. var _loop_1 = function (targetIndex) {
  103698. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  103699. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  103700. babylonAnimation.setKeys(keys.map(function (key) { return ({
  103701. frame: key.frame,
  103702. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  103703. value: key.value[targetIndex],
  103704. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  103705. }); }));
  103706. var morphTargets = new Array();
  103707. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  103708. morphTargets.push(babylonMesh.morphTargetManager.getTarget(targetIndex));
  103709. });
  103710. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  103711. };
  103712. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  103713. _loop_1(targetIndex);
  103714. }
  103715. }
  103716. else {
  103717. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  103718. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  103719. babylonAnimation.setKeys(keys);
  103720. if (targetNode._babylonAnimationTargets) {
  103721. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  103722. }
  103723. }
  103724. });
  103725. };
  103726. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  103727. if (sampler._data) {
  103728. return sampler._data;
  103729. }
  103730. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  103731. switch (interpolation) {
  103732. case "STEP" /* STEP */:
  103733. case "LINEAR" /* LINEAR */:
  103734. case "CUBICSPLINE" /* CUBICSPLINE */: {
  103735. break;
  103736. }
  103737. default: {
  103738. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  103739. }
  103740. }
  103741. var inputData;
  103742. var outputData;
  103743. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  103744. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  103745. sampler._data = Promise.all([
  103746. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  103747. inputData = data;
  103748. }),
  103749. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  103750. outputData = data;
  103751. })
  103752. ]).then(function () {
  103753. return {
  103754. input: inputData,
  103755. interpolation: interpolation,
  103756. output: outputData,
  103757. };
  103758. });
  103759. return sampler._data;
  103760. };
  103761. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  103762. if (buffer._data) {
  103763. return buffer._data;
  103764. }
  103765. if (!buffer.uri) {
  103766. throw new Error(context + ": Uri is missing");
  103767. }
  103768. buffer._data = this._loadUriAsync(context, buffer.uri);
  103769. return buffer._data;
  103770. };
  103771. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  103772. if (bufferView._data) {
  103773. return bufferView._data;
  103774. }
  103775. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  103776. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  103777. try {
  103778. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  103779. }
  103780. catch (e) {
  103781. throw new Error(context + ": " + e.message);
  103782. }
  103783. });
  103784. return bufferView._data;
  103785. };
  103786. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  103787. if (accessor.sparse) {
  103788. throw new Error(context + ": Sparse accessors are not currently supported");
  103789. }
  103790. if (accessor._data) {
  103791. return accessor._data;
  103792. }
  103793. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  103794. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  103795. var buffer = data.buffer;
  103796. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  103797. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  103798. try {
  103799. switch (accessor.componentType) {
  103800. case 5120 /* BYTE */: {
  103801. return new Int8Array(buffer, byteOffset, length);
  103802. }
  103803. case 5121 /* UNSIGNED_BYTE */: {
  103804. return new Uint8Array(buffer, byteOffset, length);
  103805. }
  103806. case 5122 /* SHORT */: {
  103807. return new Int16Array(buffer, byteOffset, length);
  103808. }
  103809. case 5123 /* UNSIGNED_SHORT */: {
  103810. return new Uint16Array(buffer, byteOffset, length);
  103811. }
  103812. case 5125 /* UNSIGNED_INT */: {
  103813. return new Uint32Array(buffer, byteOffset, length);
  103814. }
  103815. case 5126 /* FLOAT */: {
  103816. return new Float32Array(buffer, byteOffset, length);
  103817. }
  103818. default: {
  103819. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  103820. }
  103821. }
  103822. }
  103823. catch (e) {
  103824. throw new Error(context + ": " + e);
  103825. }
  103826. });
  103827. return accessor._data;
  103828. };
  103829. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  103830. var _this = this;
  103831. if (bufferView._babylonBuffer) {
  103832. return bufferView._babylonBuffer;
  103833. }
  103834. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  103835. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  103836. });
  103837. return bufferView._babylonBuffer;
  103838. };
  103839. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  103840. var _this = this;
  103841. if (accessor.sparse) {
  103842. throw new Error(context + ": Sparse accessors are not currently supported");
  103843. }
  103844. if (accessor._babylonVertexBuffer) {
  103845. return accessor._babylonVertexBuffer;
  103846. }
  103847. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  103848. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  103849. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  103850. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  103851. });
  103852. return accessor._babylonVertexBuffer;
  103853. };
  103854. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  103855. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  103856. if (!babylonMaterial) {
  103857. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  103858. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  103859. babylonMaterial.metallic = 1;
  103860. babylonMaterial.roughness = 1;
  103861. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  103862. }
  103863. return babylonMaterial;
  103864. };
  103865. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  103866. var promises = new Array();
  103867. // Ensure metallic workflow
  103868. babylonMaterial.metallic = 1;
  103869. babylonMaterial.roughness = 1;
  103870. var properties = material.pbrMetallicRoughness;
  103871. if (properties) {
  103872. if (properties.baseColorFactor) {
  103873. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  103874. babylonMaterial.alpha = properties.baseColorFactor[3];
  103875. }
  103876. else {
  103877. babylonMaterial.albedoColor = BABYLON.Color3.White();
  103878. }
  103879. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  103880. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  103881. if (properties.baseColorTexture) {
  103882. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  103883. babylonMaterial.albedoTexture = texture;
  103884. }));
  103885. }
  103886. if (properties.metallicRoughnessTexture) {
  103887. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  103888. babylonMaterial.metallicTexture = texture;
  103889. }));
  103890. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  103891. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  103892. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  103893. }
  103894. }
  103895. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  103896. return Promise.all(promises).then(function () { });
  103897. };
  103898. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  103899. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  103900. if (promise) {
  103901. return promise;
  103902. }
  103903. material._babylonData = material._babylonData || {};
  103904. var babylonData = material._babylonData[babylonDrawMode];
  103905. if (!babylonData) {
  103906. var promises = new Array();
  103907. var name_3 = material.name || "materialSG_" + material._index;
  103908. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  103909. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  103910. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  103911. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  103912. babylonData = {
  103913. material: babylonMaterial,
  103914. meshes: [],
  103915. loaded: Promise.all(promises).then(function () { })
  103916. };
  103917. material._babylonData[babylonDrawMode] = babylonData;
  103918. }
  103919. babylonData.meshes.push(babylonMesh);
  103920. assign(babylonData.material);
  103921. return babylonData.loaded;
  103922. };
  103923. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  103924. var babylonMaterial = new type(name, this._babylonScene);
  103925. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  103926. babylonMaterial.fillMode = drawMode;
  103927. return babylonMaterial;
  103928. };
  103929. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  103930. var promises = new Array();
  103931. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  103932. if (material.doubleSided) {
  103933. babylonMaterial.backFaceCulling = false;
  103934. babylonMaterial.twoSidedLighting = true;
  103935. }
  103936. if (material.normalTexture) {
  103937. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  103938. babylonMaterial.bumpTexture = texture;
  103939. }));
  103940. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  103941. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  103942. if (material.normalTexture.scale != undefined) {
  103943. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  103944. }
  103945. }
  103946. if (material.occlusionTexture) {
  103947. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  103948. babylonMaterial.ambientTexture = texture;
  103949. }));
  103950. babylonMaterial.useAmbientInGrayScale = true;
  103951. if (material.occlusionTexture.strength != undefined) {
  103952. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  103953. }
  103954. }
  103955. if (material.emissiveTexture) {
  103956. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  103957. babylonMaterial.emissiveTexture = texture;
  103958. }));
  103959. }
  103960. return Promise.all(promises).then(function () { });
  103961. };
  103962. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  103963. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  103964. switch (alphaMode) {
  103965. case "OPAQUE" /* OPAQUE */: {
  103966. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  103967. break;
  103968. }
  103969. case "MASK" /* MASK */: {
  103970. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  103971. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  103972. if (babylonMaterial.albedoTexture) {
  103973. babylonMaterial.albedoTexture.hasAlpha = true;
  103974. }
  103975. break;
  103976. }
  103977. case "BLEND" /* BLEND */: {
  103978. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  103979. if (babylonMaterial.albedoTexture) {
  103980. babylonMaterial.albedoTexture.hasAlpha = true;
  103981. babylonMaterial.useAlphaFromAlbedoTexture = true;
  103982. }
  103983. break;
  103984. }
  103985. default: {
  103986. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  103987. }
  103988. }
  103989. };
  103990. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  103991. var _this = this;
  103992. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  103993. context = "#/textures/" + textureInfo.index;
  103994. var promises = new Array();
  103995. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  103996. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  103997. var deferred = new BABYLON.Deferred();
  103998. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  103999. if (!_this._disposed) {
  104000. deferred.resolve();
  104001. }
  104002. }, function (message, exception) {
  104003. if (!_this._disposed) {
  104004. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  104005. }
  104006. });
  104007. promises.push(deferred.promise);
  104008. babylonTexture.name = texture.name || "texture" + texture._index;
  104009. babylonTexture.wrapU = samplerData.wrapU;
  104010. babylonTexture.wrapV = samplerData.wrapV;
  104011. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  104012. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  104013. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  104014. babylonTexture.updateURL(objectURL);
  104015. }));
  104016. assign(babylonTexture);
  104017. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  104018. return Promise.all(promises).then(function () { });
  104019. };
  104020. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  104021. if (!sampler._data) {
  104022. sampler._data = {
  104023. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  104024. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  104025. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  104026. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  104027. };
  104028. }
  104029. ;
  104030. return sampler._data;
  104031. };
  104032. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  104033. if (image._objectURL) {
  104034. return image._objectURL;
  104035. }
  104036. var promise;
  104037. if (image.uri) {
  104038. promise = this._loadUriAsync(context, image.uri);
  104039. }
  104040. else {
  104041. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  104042. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  104043. }
  104044. image._objectURL = promise.then(function (data) {
  104045. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  104046. });
  104047. return image._objectURL;
  104048. };
  104049. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  104050. var _this = this;
  104051. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  104052. if (promise) {
  104053. return promise;
  104054. }
  104055. if (!GLTFLoader._ValidateUri(uri)) {
  104056. throw new Error(context + ": Uri '" + uri + "' is invalid");
  104057. }
  104058. if (BABYLON.Tools.IsBase64(uri)) {
  104059. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  104060. }
  104061. return new Promise(function (resolve, reject) {
  104062. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  104063. if (!_this._disposed) {
  104064. resolve(new Uint8Array(data));
  104065. }
  104066. }, function (event) {
  104067. if (!_this._disposed) {
  104068. try {
  104069. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  104070. request._lengthComputable = event.lengthComputable;
  104071. request._loaded = event.loaded;
  104072. request._total = event.total;
  104073. _this._onProgress();
  104074. }
  104075. }
  104076. catch (e) {
  104077. reject(e);
  104078. }
  104079. }
  104080. }, _this._babylonScene.database, true, function (request, exception) {
  104081. if (!_this._disposed) {
  104082. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  104083. }
  104084. });
  104085. _this._requests.push(request);
  104086. });
  104087. };
  104088. GLTFLoader.prototype._onProgress = function () {
  104089. if (!this._progressCallback) {
  104090. return;
  104091. }
  104092. var lengthComputable = true;
  104093. var loaded = 0;
  104094. var total = 0;
  104095. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104096. var request = _a[_i];
  104097. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  104098. return;
  104099. }
  104100. lengthComputable = lengthComputable && request._lengthComputable;
  104101. loaded += request._loaded;
  104102. total += request._total;
  104103. }
  104104. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  104105. };
  104106. GLTFLoader._GetProperty = function (context, array, index) {
  104107. if (!array || index == undefined || !array[index]) {
  104108. throw new Error(context + ": Failed to find index (" + index + ")");
  104109. }
  104110. return array[index];
  104111. };
  104112. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  104113. // Set defaults if undefined
  104114. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  104115. switch (mode) {
  104116. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104117. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104118. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104119. default:
  104120. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  104121. return BABYLON.Texture.WRAP_ADDRESSMODE;
  104122. }
  104123. };
  104124. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  104125. // Set defaults if undefined
  104126. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  104127. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  104128. if (magFilter === 9729 /* LINEAR */) {
  104129. switch (minFilter) {
  104130. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  104131. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  104132. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  104133. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  104134. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  104135. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104136. default:
  104137. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104138. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104139. }
  104140. }
  104141. else {
  104142. if (magFilter !== 9728 /* NEAREST */) {
  104143. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  104144. }
  104145. switch (minFilter) {
  104146. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  104147. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  104148. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104149. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  104150. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  104151. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  104152. default:
  104153. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104154. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104155. }
  104156. }
  104157. };
  104158. GLTFLoader._GetNumComponents = function (context, type) {
  104159. switch (type) {
  104160. case "SCALAR": return 1;
  104161. case "VEC2": return 2;
  104162. case "VEC3": return 3;
  104163. case "VEC4": return 4;
  104164. case "MAT2": return 4;
  104165. case "MAT3": return 9;
  104166. case "MAT4": return 16;
  104167. }
  104168. throw new Error(context + ": Invalid type (" + type + ")");
  104169. };
  104170. GLTFLoader._ValidateUri = function (uri) {
  104171. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  104172. };
  104173. GLTFLoader._GetDrawMode = function (context, mode) {
  104174. if (mode == undefined) {
  104175. mode = 4 /* TRIANGLES */;
  104176. }
  104177. switch (mode) {
  104178. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  104179. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  104180. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  104181. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  104182. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  104183. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  104184. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  104185. }
  104186. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  104187. };
  104188. GLTFLoader.prototype._compileMaterialsAsync = function () {
  104189. var promises = new Array();
  104190. if (this._gltf.materials) {
  104191. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  104192. var material = _a[_i];
  104193. if (material._babylonData) {
  104194. for (var babylonDrawMode in material._babylonData) {
  104195. var babylonData = material._babylonData[babylonDrawMode];
  104196. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  104197. var babylonMesh = _c[_b];
  104198. // Ensure nonUniformScaling is set if necessary.
  104199. babylonMesh.computeWorldMatrix(true);
  104200. var babylonMaterial = babylonData.material;
  104201. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  104202. if (this.useClipPlane) {
  104203. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  104204. }
  104205. }
  104206. }
  104207. }
  104208. }
  104209. }
  104210. return Promise.all(promises).then(function () { });
  104211. };
  104212. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  104213. var promises = new Array();
  104214. var lights = this._babylonScene.lights;
  104215. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  104216. var light = lights_1[_i];
  104217. var generator = light.getShadowGenerator();
  104218. if (generator) {
  104219. promises.push(generator.forceCompilationAsync());
  104220. }
  104221. }
  104222. return Promise.all(promises).then(function () { });
  104223. };
  104224. GLTFLoader.prototype._clear = function () {
  104225. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104226. var request = _a[_i];
  104227. request.abort();
  104228. }
  104229. this._requests.length = 0;
  104230. if (this._gltf && this._gltf.images) {
  104231. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  104232. var image = _c[_b];
  104233. if (image._objectURL) {
  104234. image._objectURL.then(function (value) {
  104235. URL.revokeObjectURL(value);
  104236. });
  104237. image._objectURL = undefined;
  104238. }
  104239. }
  104240. }
  104241. delete this._gltf;
  104242. delete this._babylonScene;
  104243. this._completePromises.length = 0;
  104244. for (var name_4 in this._extensions) {
  104245. this._extensions[name_4].dispose();
  104246. }
  104247. this._extensions = {};
  104248. delete this._rootBabylonMesh;
  104249. delete this._progressCallback;
  104250. this.onMeshLoadedObservable.clear();
  104251. this.onTextureLoadedObservable.clear();
  104252. this.onMaterialLoadedObservable.clear();
  104253. };
  104254. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  104255. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  104256. var name_5 = _a[_i];
  104257. var extension = this._extensions[name_5];
  104258. if (extension.enabled) {
  104259. var promise = actionAsync(extension);
  104260. if (promise) {
  104261. return promise;
  104262. }
  104263. }
  104264. }
  104265. return null;
  104266. };
  104267. GLTFLoader._Names = new Array();
  104268. GLTFLoader._Factories = {};
  104269. return GLTFLoader;
  104270. }());
  104271. GLTF2.GLTFLoader = GLTFLoader;
  104272. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  104273. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104274. })(BABYLON || (BABYLON = {}));
  104275. //# sourceMappingURL=babylon.glTFLoader.js.map
  104276. var BABYLON;
  104277. (function (BABYLON) {
  104278. var GLTF2;
  104279. (function (GLTF2) {
  104280. var GLTFLoaderExtension = /** @class */ (function () {
  104281. function GLTFLoaderExtension(loader) {
  104282. this.enabled = true;
  104283. this._loader = loader;
  104284. }
  104285. GLTFLoaderExtension.prototype.dispose = function () {
  104286. delete this._loader;
  104287. };
  104288. // #region Overridable Methods
  104289. /** Override this method to modify the default behavior for loading scenes. */
  104290. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  104291. /** Override this method to modify the default behavior for loading nodes. */
  104292. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  104293. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  104294. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  104295. /** Override this method to modify the default behavior for loading materials. */
  104296. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  104297. /** Override this method to modify the default behavior for loading uris. */
  104298. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  104299. // #endregion
  104300. /** Helper method called by a loader extension to load an glTF extension. */
  104301. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  104302. if (!property.extensions) {
  104303. return null;
  104304. }
  104305. var extensions = property.extensions;
  104306. var extension = extensions[this.name];
  104307. if (!extension) {
  104308. return null;
  104309. }
  104310. // Clear out the extension before executing the action to avoid recursing into the same property.
  104311. delete extensions[this.name];
  104312. try {
  104313. return actionAsync(context + "/extensions/" + this.name, extension);
  104314. }
  104315. finally {
  104316. // Restore the extension after executing the action.
  104317. extensions[this.name] = extension;
  104318. }
  104319. };
  104320. /** Helper method called by the loader to allow extensions to override loading scenes. */
  104321. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  104322. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  104323. };
  104324. /** Helper method called by the loader to allow extensions to override loading nodes. */
  104325. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  104326. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  104327. };
  104328. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  104329. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  104330. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  104331. };
  104332. /** Helper method called by the loader to allow extensions to override loading materials. */
  104333. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  104334. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  104335. };
  104336. /** Helper method called by the loader to allow extensions to override loading uris. */
  104337. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  104338. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  104339. };
  104340. return GLTFLoaderExtension;
  104341. }());
  104342. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  104343. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104344. })(BABYLON || (BABYLON = {}));
  104345. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104346. var BABYLON;
  104347. (function (BABYLON) {
  104348. var GLTF2;
  104349. (function (GLTF2) {
  104350. var Extensions;
  104351. (function (Extensions) {
  104352. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  104353. var NAME = "MSFT_lod";
  104354. var MSFT_lod = /** @class */ (function (_super) {
  104355. __extends(MSFT_lod, _super);
  104356. function MSFT_lod() {
  104357. var _this = _super !== null && _super.apply(this, arguments) || this;
  104358. _this.name = NAME;
  104359. /**
  104360. * Maximum number of LODs to load, starting from the lowest LOD.
  104361. */
  104362. _this.maxLODsToLoad = Number.MAX_VALUE;
  104363. _this._loadingNodeLOD = null;
  104364. _this._loadNodeSignals = {};
  104365. _this._loadingMaterialLOD = null;
  104366. _this._loadMaterialSignals = {};
  104367. return _this;
  104368. }
  104369. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  104370. var _this = this;
  104371. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  104372. var firstPromise;
  104373. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  104374. var _loop_1 = function (indexLOD) {
  104375. var nodeLOD = nodeLODs[indexLOD];
  104376. if (indexLOD !== 0) {
  104377. _this._loadingNodeLOD = nodeLOD;
  104378. if (!_this._loadNodeSignals[nodeLOD._index]) {
  104379. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  104380. }
  104381. }
  104382. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  104383. if (indexLOD !== 0) {
  104384. var previousNodeLOD = nodeLODs[indexLOD - 1];
  104385. if (previousNodeLOD._babylonMesh) {
  104386. previousNodeLOD._babylonMesh.dispose(false, true);
  104387. delete previousNodeLOD._babylonMesh;
  104388. }
  104389. }
  104390. if (indexLOD !== nodeLODs.length - 1) {
  104391. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  104392. if (_this._loadNodeSignals[nodeIndex]) {
  104393. _this._loadNodeSignals[nodeIndex].resolve();
  104394. delete _this._loadNodeSignals[nodeIndex];
  104395. }
  104396. }
  104397. });
  104398. if (indexLOD === 0) {
  104399. firstPromise = promise;
  104400. }
  104401. else {
  104402. _this._loader._completePromises.push(promise);
  104403. _this._loadingNodeLOD = null;
  104404. }
  104405. };
  104406. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  104407. _loop_1(indexLOD);
  104408. }
  104409. return firstPromise;
  104410. });
  104411. };
  104412. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104413. var _this = this;
  104414. // Don't load material LODs if already loading a node LOD.
  104415. if (this._loadingNodeLOD) {
  104416. return null;
  104417. }
  104418. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  104419. var firstPromise;
  104420. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  104421. var _loop_2 = function (indexLOD) {
  104422. var materialLOD = materialLODs[indexLOD];
  104423. if (indexLOD !== 0) {
  104424. _this._loadingMaterialLOD = materialLOD;
  104425. if (!_this._loadMaterialSignals[materialLOD._index]) {
  104426. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  104427. }
  104428. }
  104429. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  104430. if (indexLOD !== 0) {
  104431. var babylonDataLOD = materialLOD._babylonData;
  104432. assign(babylonDataLOD[babylonDrawMode].material);
  104433. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  104434. if (previousBabylonDataLOD[babylonDrawMode]) {
  104435. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  104436. delete previousBabylonDataLOD[babylonDrawMode];
  104437. }
  104438. }
  104439. if (indexLOD !== materialLODs.length - 1) {
  104440. var materialIndex = materialLODs[indexLOD + 1]._index;
  104441. if (_this._loadMaterialSignals[materialIndex]) {
  104442. _this._loadMaterialSignals[materialIndex].resolve();
  104443. delete _this._loadMaterialSignals[materialIndex];
  104444. }
  104445. }
  104446. });
  104447. if (indexLOD === 0) {
  104448. firstPromise = promise;
  104449. }
  104450. else {
  104451. _this._loader._completePromises.push(promise);
  104452. _this._loadingMaterialLOD = null;
  104453. }
  104454. };
  104455. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  104456. _loop_2(indexLOD);
  104457. }
  104458. return firstPromise;
  104459. });
  104460. };
  104461. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  104462. var _this = this;
  104463. // Defer the loading of uris if loading a material or node LOD.
  104464. if (this._loadingMaterialLOD) {
  104465. var index = this._loadingMaterialLOD._index;
  104466. return this._loadMaterialSignals[index].promise.then(function () {
  104467. return _this._loader._loadUriAsync(context, uri);
  104468. });
  104469. }
  104470. else if (this._loadingNodeLOD) {
  104471. var index = this._loadingNodeLOD._index;
  104472. return this._loadNodeSignals[index].promise.then(function () {
  104473. return _this._loader._loadUriAsync(context, uri);
  104474. });
  104475. }
  104476. return null;
  104477. };
  104478. /**
  104479. * Gets an array of LOD properties from lowest to highest.
  104480. */
  104481. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  104482. if (this.maxLODsToLoad <= 0) {
  104483. throw new Error("maxLODsToLoad must be greater than zero");
  104484. }
  104485. var properties = new Array();
  104486. for (var i = ids.length - 1; i >= 0; i--) {
  104487. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  104488. if (properties.length === this.maxLODsToLoad) {
  104489. return properties;
  104490. }
  104491. }
  104492. properties.push(property);
  104493. return properties;
  104494. };
  104495. return MSFT_lod;
  104496. }(GLTF2.GLTFLoaderExtension));
  104497. Extensions.MSFT_lod = MSFT_lod;
  104498. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  104499. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104500. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104501. })(BABYLON || (BABYLON = {}));
  104502. //# sourceMappingURL=MSFT_lod.js.map
  104503. var BABYLON;
  104504. (function (BABYLON) {
  104505. var GLTF2;
  104506. (function (GLTF2) {
  104507. var Extensions;
  104508. (function (Extensions) {
  104509. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  104510. var NAME = "KHR_draco_mesh_compression";
  104511. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  104512. __extends(KHR_draco_mesh_compression, _super);
  104513. function KHR_draco_mesh_compression(loader) {
  104514. var _this = _super.call(this, loader) || this;
  104515. _this.name = NAME;
  104516. _this._dracoCompression = null;
  104517. // Disable extension if decoder is not available.
  104518. if (!BABYLON.DracoCompression.DecoderAvailable) {
  104519. _this.enabled = false;
  104520. }
  104521. return _this;
  104522. }
  104523. KHR_draco_mesh_compression.prototype.dispose = function () {
  104524. if (this._dracoCompression) {
  104525. this._dracoCompression.dispose();
  104526. }
  104527. _super.prototype.dispose.call(this);
  104528. };
  104529. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104530. var _this = this;
  104531. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  104532. if (primitive.mode != undefined) {
  104533. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  104534. primitive.mode !== 4 /* TRIANGLES */) {
  104535. throw new Error(context + ": Unsupported mode " + primitive.mode);
  104536. }
  104537. // TODO: handle triangle strips
  104538. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  104539. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  104540. }
  104541. }
  104542. var attributes = {};
  104543. var loadAttribute = function (name, kind) {
  104544. var uniqueId = extension.attributes[name];
  104545. if (uniqueId == undefined) {
  104546. return;
  104547. }
  104548. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104549. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104550. babylonMesh._delayInfo.push(kind);
  104551. }
  104552. attributes[kind] = uniqueId;
  104553. };
  104554. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104555. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104556. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104557. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104558. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104559. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104560. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104561. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  104562. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  104563. if (!bufferView._dracoBabylonGeometry) {
  104564. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104565. if (!_this._dracoCompression) {
  104566. _this._dracoCompression = new BABYLON.DracoCompression();
  104567. }
  104568. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  104569. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  104570. babylonVertexData.applyToGeometry(babylonGeometry);
  104571. return babylonGeometry;
  104572. }).catch(function (error) {
  104573. throw new Error(context + ": " + error.message);
  104574. });
  104575. });
  104576. }
  104577. return bufferView._dracoBabylonGeometry;
  104578. });
  104579. };
  104580. return KHR_draco_mesh_compression;
  104581. }(GLTF2.GLTFLoaderExtension));
  104582. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  104583. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  104584. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104585. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104586. })(BABYLON || (BABYLON = {}));
  104587. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  104588. var BABYLON;
  104589. (function (BABYLON) {
  104590. var GLTF2;
  104591. (function (GLTF2) {
  104592. var Extensions;
  104593. (function (Extensions) {
  104594. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  104595. var NAME = "KHR_materials_pbrSpecularGlossiness";
  104596. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  104597. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  104598. function KHR_materials_pbrSpecularGlossiness() {
  104599. var _this = _super !== null && _super.apply(this, arguments) || this;
  104600. _this.name = NAME;
  104601. return _this;
  104602. }
  104603. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104604. var _this = this;
  104605. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  104606. material._babylonData = material._babylonData || {};
  104607. var babylonData = material._babylonData[babylonDrawMode];
  104608. if (!babylonData) {
  104609. var promises = new Array();
  104610. var name_1 = material.name || "materialSG_" + material._index;
  104611. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  104612. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104613. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  104614. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104615. babylonData = {
  104616. material: babylonMaterial,
  104617. meshes: [],
  104618. loaded: Promise.all(promises).then(function () { })
  104619. };
  104620. material._babylonData[babylonDrawMode] = babylonData;
  104621. }
  104622. babylonData.meshes.push(babylonMesh);
  104623. assign(babylonData.material);
  104624. return babylonData.loaded;
  104625. });
  104626. };
  104627. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  104628. var promises = new Array();
  104629. if (properties.diffuseFactor) {
  104630. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  104631. babylonMaterial.alpha = properties.diffuseFactor[3];
  104632. }
  104633. else {
  104634. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104635. }
  104636. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  104637. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  104638. if (properties.diffuseTexture) {
  104639. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  104640. babylonMaterial.albedoTexture = texture;
  104641. }));
  104642. }
  104643. if (properties.specularGlossinessTexture) {
  104644. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  104645. babylonMaterial.reflectivityTexture = texture;
  104646. }));
  104647. babylonMaterial.reflectivityTexture.hasAlpha = true;
  104648. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  104649. }
  104650. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104651. return Promise.all(promises).then(function () { });
  104652. };
  104653. return KHR_materials_pbrSpecularGlossiness;
  104654. }(GLTF2.GLTFLoaderExtension));
  104655. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  104656. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  104657. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104658. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104659. })(BABYLON || (BABYLON = {}));
  104660. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  104661. var BABYLON;
  104662. (function (BABYLON) {
  104663. var GLTF2;
  104664. (function (GLTF2) {
  104665. var Extensions;
  104666. (function (Extensions) {
  104667. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  104668. var NAME = "KHR_materials_unlit";
  104669. var KHR_materials_unlit = /** @class */ (function (_super) {
  104670. __extends(KHR_materials_unlit, _super);
  104671. function KHR_materials_unlit() {
  104672. var _this = _super !== null && _super.apply(this, arguments) || this;
  104673. _this.name = NAME;
  104674. return _this;
  104675. }
  104676. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104677. var _this = this;
  104678. return this._loadExtensionAsync(context, material, function () {
  104679. material._babylonData = material._babylonData || {};
  104680. var babylonData = material._babylonData[babylonDrawMode];
  104681. if (!babylonData) {
  104682. var name_1 = material.name || "materialUnlit_" + material._index;
  104683. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  104684. babylonMaterial.unlit = true;
  104685. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  104686. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104687. babylonData = {
  104688. material: babylonMaterial,
  104689. meshes: [],
  104690. loaded: promise
  104691. };
  104692. material._babylonData[babylonDrawMode] = babylonData;
  104693. }
  104694. babylonData.meshes.push(babylonMesh);
  104695. assign(babylonData.material);
  104696. return babylonData.loaded;
  104697. });
  104698. };
  104699. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  104700. var promises = new Array();
  104701. // Ensure metallic workflow
  104702. babylonMaterial.metallic = 1;
  104703. babylonMaterial.roughness = 1;
  104704. var properties = material.pbrMetallicRoughness;
  104705. if (properties) {
  104706. if (properties.baseColorFactor) {
  104707. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104708. babylonMaterial.alpha = properties.baseColorFactor[3];
  104709. }
  104710. else {
  104711. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104712. }
  104713. if (properties.baseColorTexture) {
  104714. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104715. babylonMaterial.albedoTexture = texture;
  104716. }));
  104717. }
  104718. }
  104719. if (material.doubleSided) {
  104720. babylonMaterial.backFaceCulling = false;
  104721. babylonMaterial.twoSidedLighting = true;
  104722. }
  104723. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104724. return Promise.all(promises).then(function () { });
  104725. };
  104726. return KHR_materials_unlit;
  104727. }(GLTF2.GLTFLoaderExtension));
  104728. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  104729. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  104730. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104731. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104732. })(BABYLON || (BABYLON = {}));
  104733. //# sourceMappingURL=KHR_materials_unlit.js.map
  104734. var BABYLON;
  104735. (function (BABYLON) {
  104736. var GLTF2;
  104737. (function (GLTF2) {
  104738. var Extensions;
  104739. (function (Extensions) {
  104740. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  104741. var NAME = "KHR_lights";
  104742. var LightType;
  104743. (function (LightType) {
  104744. LightType["AMBIENT"] = "ambient";
  104745. LightType["DIRECTIONAL"] = "directional";
  104746. LightType["POINT"] = "point";
  104747. LightType["SPOT"] = "spot";
  104748. })(LightType || (LightType = {}));
  104749. var KHR_lights = /** @class */ (function (_super) {
  104750. __extends(KHR_lights, _super);
  104751. function KHR_lights() {
  104752. var _this = _super !== null && _super.apply(this, arguments) || this;
  104753. _this.name = NAME;
  104754. return _this;
  104755. }
  104756. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  104757. var _this = this;
  104758. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  104759. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  104760. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  104761. if (light.type !== LightType.AMBIENT) {
  104762. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  104763. }
  104764. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  104765. return promise;
  104766. });
  104767. };
  104768. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  104769. var _this = this;
  104770. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  104771. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  104772. var babylonLight;
  104773. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  104774. var name = node._babylonMesh.name;
  104775. switch (light.type) {
  104776. case LightType.AMBIENT: {
  104777. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  104778. }
  104779. case LightType.DIRECTIONAL: {
  104780. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  104781. break;
  104782. }
  104783. case LightType.POINT: {
  104784. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  104785. break;
  104786. }
  104787. case LightType.SPOT: {
  104788. var spotLight = light;
  104789. // TODO: support inner and outer cone angles
  104790. //const innerConeAngle = spotLight.innerConeAngle || 0;
  104791. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  104792. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  104793. break;
  104794. }
  104795. default: {
  104796. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  104797. }
  104798. }
  104799. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  104800. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  104801. babylonLight.parent = node._babylonMesh;
  104802. return promise;
  104803. });
  104804. };
  104805. Object.defineProperty(KHR_lights.prototype, "_lights", {
  104806. get: function () {
  104807. var extensions = this._loader._gltf.extensions;
  104808. if (!extensions || !extensions[this.name]) {
  104809. throw new Error("#/extensions: '" + this.name + "' not found");
  104810. }
  104811. var extension = extensions[this.name];
  104812. return extension.lights;
  104813. },
  104814. enumerable: true,
  104815. configurable: true
  104816. });
  104817. return KHR_lights;
  104818. }(GLTF2.GLTFLoaderExtension));
  104819. Extensions.KHR_lights = KHR_lights;
  104820. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  104821. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104822. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104823. })(BABYLON || (BABYLON = {}));
  104824. //# sourceMappingURL=KHR_lights.js.map
  104825. return BABYLON;
  104826. });
  104827. /***/ }),
  104828. /* 35 */
  104829. /***/ (function(module, exports, __webpack_require__) {
  104830. /*!
  104831. * PEP v0.4.3 | https://github.com/jquery/PEP
  104832. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  104833. */
  104834. !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);
  104835. // define inherited MouseEvent properties
  104836. // skip bubbles and cancelable since they're set above in initEvent()
  104837. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  104838. // Spec requires that pointers without pressure specified use 0.5 for down
  104839. // state and 0 for up state.
  104840. var f=0;
  104841. // add x/y properties aliased to clientX/Y
  104842. // define the properties of the PointerEvent interface
  104843. 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(){
  104844. // only activate if this platform does not have pointer events
  104845. 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}})}/**
  104846. * This is the constructor for new PointerEvents.
  104847. *
  104848. * New Pointer Events must be given a type, and an optional dictionary of
  104849. * initialization properties.
  104850. *
  104851. * Due to certain platform requirements, events returned from the constructor
  104852. * identify as MouseEvents.
  104853. *
  104854. * @constructor
  104855. * @param {String} inType The type of the event to create.
  104856. * @param {Object} [inDict] An optional dictionary of initial event properties.
  104857. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  104858. */
  104859. 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},
  104860. // return value, key, map
  104861. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  104862. // MouseEvent
  104863. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  104864. // DOM Level 3
  104865. "buttons",
  104866. // PointerEvent
  104867. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  104868. // event instance
  104869. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  104870. // MouseEvent
  104871. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  104872. // DOM Level 3
  104873. 0,
  104874. // PointerEvent
  104875. 0,0,0,0,0,0,"",0,!1,
  104876. // event instance
  104877. "",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),
  104878. // Scope objects for native events.
  104879. // This exists for ease of testing.
  104880. eventSources:Object.create(null),eventSourceList:[],/**
  104881. * Add a new event source that will generate pointer events.
  104882. *
  104883. * `inSource` must contain an array of event names named `events`, and
  104884. * functions with the names specified in the `events` array.
  104885. * @param {string} name A name for the event source
  104886. * @param {Object} source A new source of platform events.
  104887. */
  104888. 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++)
  104889. // call eventsource register
  104890. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  104891. // call eventsource register
  104892. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  104893. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  104894. return!1}},
  104895. // EVENTS
  104896. 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)},
  104897. // LISTENER LOGIC
  104898. eventHandler:function(a){
  104899. // This is used to prevent multiple dispatch of pointerevents from
  104900. // platform events. This can happen when two elements in different scopes
  104901. // are set up to create pointer events, which is relevant to Shadow DOM.
  104902. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  104903. // set up event listeners
  104904. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  104905. // remove event listeners
  104906. 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)},
  104907. // EVENT CREATION AND TRACKING
  104908. /**
  104909. * Creates a new Event of type `inType`, based on the information in
  104910. * `inEvent`.
  104911. *
  104912. * @param {string} inType A string representing the type of event to create
  104913. * @param {Event} inEvent A platform event with a target
  104914. * @return {Event} A PointerEvent of type `inType`
  104915. */
  104916. makeEvent:function(b,c){
  104917. // relatedTarget must be null if pointer is captured
  104918. 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},
  104919. // make and dispatch an event in one call
  104920. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  104921. * Returns a snapshot of inEvent, with writable properties.
  104922. *
  104923. * @param {Event} inEvent An event that contains properties to copy.
  104924. * @return {Object} An object containing shallow copies of `inEvent`'s
  104925. * properties.
  104926. */
  104927. 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],
  104928. // Work around SVGInstanceElement shadow tree
  104929. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  104930. // This is the behavior implemented by Firefox.
  104931. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  104932. // keep the semantics of preventDefault
  104933. 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){
  104934. // Order of conditions due to document.contains() missing in IE.
  104935. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  104936. // Touch: Do not propagate if node is detached.
  104937. 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)}},/**
  104938. * Dispatches the event to its target.
  104939. *
  104940. * @param {Event} inEvent The event to be dispatched.
  104941. * @return {Boolean} True if an event handler returns true, false otherwise.
  104942. */
  104943. 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(
  104944. // is element a shadow host?
  104945. e=this.targetingShadow(f);e;){if(
  104946. // find the the element inside the shadow root
  104947. d=e.elementFromPoint(b,c)){
  104948. // shadowed element may contain a shadow root
  104949. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  104950. // check for older shadows
  104951. e=this.olderShadow(e)}
  104952. // light dom element is the target
  104953. return f}},owner:function(a){
  104954. // walk up until you hit the shadow root or document
  104955. for(var b=a;b.parentNode;)b=b.parentNode;
  104956. // the owner element is expected to be a Document or ShadowRoot
  104957. 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);
  104958. // if x, y is not in this root, fall back to document search
  104959. 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){
  104960. // Only watch scopes that can target find, as these are top-level.
  104961. // Otherwise we can see duplicate additions and removals that add noise.
  104962. //
  104963. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  104964. // a removal without an insertion when a node is redistributed among
  104965. // shadows. Since it all ends up correct in the document, watching only
  104966. // the document will yield the correct mutations to watch.
  104967. 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))},
  104968. // register all touch-action = none nodes on document load
  104969. 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){
  104970. // find children with touch-action
  104971. var b=x(a,this.findElements,this);
  104972. // flatten the list
  104973. // make sure the added nodes are accounted for
  104974. 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){}
  104975. // handler block for native mouse events
  104976. 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:[],
  104977. // collide with the global mouse listener
  104978. 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++){
  104979. // simulated mouse events will be swallowed near a primary touchend
  104980. 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);
  104981. // Update buttons state after possible out-of-document mouseup.
  104982. 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];
  104983. // Produces wrong state of buttons in Browsers without `buttons` support
  104984. // when a mouse button that was pressed outside the document is released
  104985. // inside and other buttons are still pressed down.
  104986. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  104987. // Support: Firefox <=44 only
  104988. // FF Ubuntu includes the lifted button in the `buttons` property on
  104989. // mouseup.
  104990. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  104991. 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),
  104992. // set touch-action on shadows as well
  104993. 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),
  104994. // remove touch-action from shadow
  104995. 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);
  104996. // simply update scrollType if listeners are already established
  104997. 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){
  104998. // set primary touch if there no pointers, or the only pointer is the mouse
  104999. (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,
  105000. // forward modifier keys
  105001. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  105002. // forward touch preventDefaults
  105003. 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))},
  105004. // For single axis scrollers, determines whether the element should emit
  105005. // pointer events or behave as a scroller
  105006. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  105007. // this element is a touch-action: none, should never scroll
  105008. b=!1;else if("XY"===c)
  105009. // this element should always scroll
  105010. 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]);
  105011. // if delta in the scroll axis > delta other axis, scroll instead of
  105012. // making events
  105013. 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},
  105014. // In some instances, a touchstart can happen without a touchend. This
  105015. // leaves the pointermap in a broken state.
  105016. // Therefore, on every touchstart, we remove the touches that did not fire a
  105017. // touchend event.
  105018. // To keep state globally consistent, we fire a
  105019. // pointercancel for this "abandoned" touch
  105020. vacuumTouches:function(a){var b=a.touches;
  105021. // pointermap.size should be < tl.length here, as the touchstart has not
  105022. // been processed yet.
  105023. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  105024. // Never remove pointerId == 1, which is mouse.
  105025. // Touch identifiers are 2 smaller than their pointerId, which is the
  105026. // index in pointermap.
  105027. 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);
  105028. // a finger drifted off the screen, ignore it
  105029. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  105030. // recover from retargeting by shadow
  105031. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  105032. // clean up case when finger leaves the screen
  105033. 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)},
  105034. // prevent synth mouse events from creating pointer events
  105035. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  105036. // only the primary finger will synth mouse events
  105037. if(this.isPrimaryTouch(c)){
  105038. // remember x/y of last touch
  105039. 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});
  105040. /***/ }),
  105041. /* 36 */
  105042. /***/ (function(module, exports, __webpack_require__) {
  105043. "use strict";
  105044. Object.defineProperty(exports, "__esModule", { value: true });
  105045. var defaultViewer_1 = __webpack_require__(5);
  105046. var mappers_1 = __webpack_require__(1);
  105047. /**
  105048. * Select all HTML tags on the page that match the selector and initialize a viewer
  105049. *
  105050. * @param selector the selector to initialize the viewer on (default is 'babylon')
  105051. */
  105052. function InitTags(selector) {
  105053. if (selector === void 0) { selector = 'babylon'; }
  105054. var elements = document.querySelectorAll(selector);
  105055. for (var i = 0; i < elements.length; ++i) {
  105056. var element = elements.item(i);
  105057. // get the html configuration
  105058. var configMapper = mappers_1.mapperManager.getMapper('dom');
  105059. var config = configMapper.map(element);
  105060. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  105061. }
  105062. }
  105063. exports.InitTags = InitTags;
  105064. /***/ })
  105065. /******/ ]);
  105066. return BabylonViewer;
  105067. });